Reputation: 3592
I have a form containing 2 input fields, one being hidden and a button. When I click on the button, I need to get and assign the value of the hidden form field within that same form to another div.
How do I iterate through the dom to get the value of that specific form field? I know the form input field name.
[EDIT] - I should have added that I have multiple forms with on the same page with the same elements, so I cannot use $("input[name='FORMELEMENT']"); as I have a variety of the same form names. I need to find the value of the form element in the same form as where the button is located.
Upvotes: 0
Views: 11155
Reputation: 49198
Note, the input
is type="text"
to make it easier to see the change. This doesn't affect it being a type="hidden"
in the live example, as they both function essentially the same, except one is not visible.
EDIT - Note, made a change after realizing the console.log()
s weren't working as expected.
<form>
<input type="text" name="myhidden" value="[placeholder]"/>
<input type="button" name="mybutton" value="Click me!" rel="the value to copy 1"/>
</form>
<form>
<input type="text" name="myhidden" value="[placeholder]"/>
<input type="button" name="mybutton" value="Click me!" rel="the value to copy 2"/>
</form>
<form>
<input type="text" name="myhidden" value="[placeholder]"/>
<input type="button" name="mybutton" value="Click me!" rel="the value to copy 3"/>
</form>
$(document).ready(function(){
$('input[name="mybutton"]').click(function(){
var $hidden = $(this).parent('form').find('input[name="myhidden"]');
console.log($hidden.val());
$hidden.val($(this).attr('rel'));
console.log($hidden.val());
});
});
Upvotes: 2
Reputation: 25701
Unless you really want to iterate through the DOM, you're better off just giving the form elements IDs, which makes the code easier and more reliable.
And then add this function to your Javascript file
function copyFormValue(visibleID, hiddenID){
visibleElement = document.getElementById(visibleID);
hiddenElement = document.getElementById(hiddenID);
hiddenElement.value = visibleElement.value;
}
And call the function when your button is clicked.
onclick="copyFormValue('userName', 'userNameHidden');"
Upvotes: 0