简体   繁体   中英

JQuery to get input field value based on label

I need to copy the value of the first input box to the second input box. The id and name of these input boxes are coming from tables. What is fix will be the labels like 'Code' and 'Copy Code'

<label>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label>Copy Code</label>
<input type="text" value=""  id="custcode_2" />

For normal scenario it will be just

$('#custcode_2').val($('#custcode_1').val());

But the id or name are generated on the fly so this is not possible. How to achieve this using labels of the input boxes.
Thanks for the help.

i think you can store the data value at data- attributes:

<label id="code" data-value="1234">
<label id="copy_code" data-value="">

and then copy the value of code to copy_code using

$('#copy_code').data('value', $('#code').data('value'))

You could loop through the inputs and in this loop grab the previous input of the current one. From there you take it's value.

 $('input').each(function(i, e) { var previousSibling = $(this).prevAll('input').first(); if (previousSibling.length) { $(this).val(previousSibling.val()); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label>Code</label> <input type="text" value="1234" id="custcode_1" /> <label>Copy Code</label> <input type="text" value="" id="custcode_2" /> 

You can wrap the elements in a span or div with a class and then use that as your scope.

<span class="custWrapper">
<label>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label>Copy Code</label>
<input type="text" value=""  id="custcode_2" />
</span>

$('.custWrapper').on('load', function(){
    var inpts = $(this).find('input');

    $(inpts[1]).val($(inpts[0]).val());
});

You could try something like this after giving id for both the label's.

HTML:

<label id='Code'>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label id='CopyCode'>Copy Code</label>
<input type="text" value=""  id="custcode_2" />

JQuery:

$(function(){

$('label').text('Copy Code').next('input[type=text]').val($('label').text('Code').next('input[type=text]').val());

});

You can use this code,

//Find the input textbox with label Code
var $copy = $('label').filter(function () {
    return this.firstChild.nodeValue.trim() === 'Code';
}).next('input');

//Find the input textbox with label Copy Code
var $copycode = $('label').filter(function () {
    return this.firstChild.nodeValue.trim() === 'Copy Code';
}).next('input');

//Copy the value
$copycode.val($copy.val());

//Copy the value as character typed into the textbox
$('input').on('keyup',function(){
$copycode.val($copy.val());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM