Change a hidden input fields value when a radio button is selected - javascript

I want to change the value of an hidden input field each time a user checks a radio button.
This is how my HTML looks like.
<input type="hidden" id="ZAAL_NAME" value="" name="ZAAL_NAME" />
<input type="radio" name="zaal_ID" value="ROOM1" onclick="change">
<input type="radio" name="zaal_ID" value="ROOM2" onclick="change">
<input type="radio" name="zaal_ID" value="ROOM3" onclick="change">
Now I want that each time I check a radio button, the value of that radio button becomes also the value of the hidden input field. Does anybody knows how to do that? Here is what I have so far.
$('input[name="radbut"]').click(function() {
console.log(this.value);
$('ZAAL_NAME').val(this.value);
});
Could anybody help ?
Kind regards,
Steaphann

Your inline onclick handler won't work since you didn't include parentheses: it needs to be onclick="change()" to actually call your function. But you should change it to onclick="change(this);" to pass a reference to the clicked button to your function, then:
function change(el){
$("#ZAAL_NAME").val(el.value) ;
}
Also you jQuery selector need a # to select by id.
Better though would be to remove the inline onclick from your markup and do it like this:
$('input[name="zaal_ID"]').click(function() {
$('#ZAAL_NAME').val(this.value);
});
The latter would need to be in a document ready handler and/or in a script block that appears after your radio buttons in the page source.
Note: when getting the value of the clicked element you can say $(el).val() or $(this).val() (depending on which of the two functions you are looking at), but given that el and this are references to the DOM element you can just get its value property directly with el.value or this.value.

$('input[name="zaal_ID"]').change(function(){
$('#ZAAL_NAME').val( this.value );
})

function change(){
$("ZAAL_NAME").val( $(this).val() ) ;
}
or
function change(){
$("ZAAL_NAME").val($("input[type='radio']:checked").val()) ;
}

try -
$(':radio').change(function(){
$('#ZAAL_NAME').val($(this).val());
})
Demo: http://jsfiddle.net/KMXnR/

use onclick="change(this.value);" and the function use like this
function change(e){
$("ZAAL_NAME").val(e) ;
}

You can use is
$("input:radio[name=ZAAL_NAME]").click(function() {
var value = $(this).val();
// or $('input:radio[name=theme]:checked').val();
$("#ZAAL_NAME").val(value);
});
in short
$("input:radio[name=ZAAL_NAME]").click(function() {
$("#ZAAL_NAME").val( $(this).val() );
});

Related

Change value of two input fields to the same value, regardless of which field is used

I have two fields on my product's page, using the class '.qty'. What I want to achieve is that when I enter a value in either of the input fields, both of these input fields are filled with that value.
My current code is this:
function updateProductAmount() {
jQuery('.add-to-cart .qty').each(function() {
var productAmount = this.value;
jQuery('.add-to-cart .qty').val(productAmount);
// Requires more work.
});
}
I'm calling this code with an onchange inside the input text elements.
This code, however only works one way. When the first input element is changed, it copies the value to the last input element. However, when the last input element is changed, it changes back to the value of the first input element.
Can anyone point out to me what I'm doing wrong and help me out?
Thanks in advance.
Try the following:
$(document).on('change','.add-to-cart .qty', function(){
$('.add-to-cart .qty').val($(this).val());
});
Js Fiddle Example
Try passing the used inputfield as parameter.
ex:
to check which field was used.
You could also pass a reference to 2nd field (if it is intended that you stick to two fields. Something along the lines should do the trick
<input type="text" value="" name="qty" class="qty" onchange="updateProductAmount(this, jQuery('.add-to-cart'))"/>
<input type="text" value="" name="add-to-cart" class="add-to-cart" onchange="updateProductAmount(this, jQuery('.qty'))"/>
and on the script-part
function updateProductAmount(caller, fieldToChange) {
jQuery(fieldToChange).val(caller.value);
}
If I understand, you need change value of siblings
jQuery( '.add-to-cart .qty' ).on( 'change' , function () {
jQuery( this ).siblings().val( jQuery( this ).val() );
} );
Try this :
$(document).ready(function() {
$(".qty").on("input",function(){
$(".qty").not($(this)).val($(this).val());
})
})
Final code :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="text" class="qty" value="" />
<input type="text" class="qty" value="" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".qty").on("input",function(){
$(".qty").not($(this)).val($(this).val());
})
})
</script>
</body>
</html>
Here is a JS fiddle of what you are trying to do.
function updateProductAmount() {
$('.qty').val($(this).val());
}
$(".qty").change(updateProductAmount);
https://jsfiddle.net/ahmedhawas7/zx3sqxft/
The problem here is that you are setting each value for each input. If you trace the code you'll see something like this:
Change the first input
updateProductAmount is invoked
.each is called so we run your function for all elements matching the '.add-to-cart .qty' selector (both inputs)
We save off the value of "this" input, which will be the first input found by .each, or the input we actually changed
Then the code "jQuery('.add-to-cart .qty').val(productAmount);" will set the value of "productAmount" to all elements that match the '.add-to-cart .qty' selector, which is both inputs. This means that input 2 now has the value of input 1, like we wanted.
Our .each now moves to the second element in the list, retrieves the value of that second input which is equal to the value of the first element by step 5, and sets the value of both inputs to that (which doesn't actually change anything since they both have this value already).
Now, as you can see, if the second input is changed the same order of operations occurs. This means that the first input will be examined first, and its value will be given to all inputs matching the selector, overwriting the value of the second input with the first. Therefore, it doesn't matter what the value of the second input is because by the time the .each gets there it has already been overwritten with the value from input 1.
As others have said, the solution here is to simply find all matching elements you would like to update with jQuery and set them to this.value. Using the jQuery val function updates the value of all matched elements, eliminating the need for a .each loop:
function updateProductAmount() {
$('.add-to-cart .qty').val(this.value);
}
The value of this within jQuery's each() is the value of the object for this iteration of each(), not the element on which the event was fired. You need to store the value to which you are changing the input prior to entering the each().
You then use a second jQuery statement with the each() with the same selector to change the value. This causes all values to be first changed to the first <input>'s value, then changed to the second <input>'s value, then to the third, etc. However, by the time you get to changing all <input> values to the second <input>'s value, the second <input>'s value has already been changed to the value of the first <input>. Effectively, this results in all <input>s following the value of the first <input> without being able to change any input other than the first.
Example showing value of this within each():
$('.add-to-cart input.qty').on('input', updateProductAmount);
function updateProductAmount() {
$('.add-to-cart input.qty').each(function() {
console.log('This points to id: ' + this.id + " ::value=" + this.value);
var productAmount = this.value;
$('.add-to-cart .qty').val(productAmount);
// Requires more work.
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-to-cart">
<input class="qty" id="firstInput">
<input class="qty" id="secondInput">
</div>
Minimally changed, functional: store productAmount before the each():
$('.add-to-cart input.qty').on('input', updateProductAmount);
function updateProductAmount() {
var productAmount = this.value;
$('.add-to-cart input.qty').each(function() {
$('.add-to-cart .qty').val(productAmount);
// Requires more work.
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-to-cart">
<input class="qty" id="firstInput">
<input class="qty" id="secondInput">
</div>
In addition:
There is no need to change the value for the element on which the event is being fired. Thus, you can use .not($(this)) to remove it from the jQuery object over which you are iterating with each().
You, potentially, are iterating over elements that are not <input>s. You can change your selector to only select <input> elements.
Having removed the var productAmount = this.value; from within your each() it is no longer necessary to explicitly iterate over the jQuery object using each(). You can use jQuery's implicit iteration to change the value using val().
$('.add-to-cart input.qty').on('input', updateProductAmount);
function updateProductAmount() {
var productAmount = this.value;
$('.add-to-cart input.qty').not($(this)).val(productAmount);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-to-cart">
<input class="qty" id="firstInput">
<input class="qty" id="secondInput">
</div>
Now that you are not using each(), this will refer to the element on which the event is fired. Thus, there is no need to first store the value in a separate variable. However, if you are expecting to iterate over a large number of elements, then using a separate variable will be slightly faster than getting the value from the element in each iteration.
Final code:
$('.add-to-cart input.qty').on('input', updateProductAmount);
function updateProductAmount() {
$('.add-to-cart input.qty').not($(this)).val(this.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-to-cart">
<input class="qty" id="firstInput">
<input class="qty" id="secondInput">
</div>

an event that fire's when the textbox is changing from another element

i have 4 textbox's on my form 3 of them change the last textbox value every time they
assign new values.
iam trying to create an event that will trigger every time the last textbox value as changed
not only when the textbox leave focus or key up an down.
i tried this code but it doesn't work
<input class='textbox' type='text'/>
<input class='textbox' type='text'/>
<input class='textbox' type='text'/>
<input id='hex_color_textbox' class='textbox' type='text'/>
$("#hex_color_textbox").on('change keyup paste', function()
{
});
any ideas?
thank you
If you want your code to react when the user is typing/pasting something, you can just say:
$("#hex_color_textbox").on('input', function()
{
//do your stuff
});
Here is the example: http://jsfiddle.net/dwYeC/
you should put the change event on the other input's if you want the last input to be changed to the value of one of the three textboxes
$("input:not('#hex_color_textbox')").on("change", function() {
var val = $(this).val()
$("#hex_color_textbox").val(val);
});
I have tried your code on jsbin.com and it works as you described with no problem.
I used jquery 1.8
see code
what kind of browser are you using and what version of jQuery?
try below:-
$('#hex_color_textbox').change(function(){
// do operation according to Your requirement
alert("the value has changed");
});

jQuery input value not working

Have looked for a solution to this but not found one.
$(document).ready(function() {
if ($("input").value()) {
$("h1").hide();
}
}
So this does not seem to be working ( $("h1").hide() is just a placeholder action... that part is not important, the problem is that the if statement is not working).
There is one form on the page, <input type=text>. I want to make it so that at all times, if there is any text in the input box a certain state is applied. If the input box returns to empty then the state is removed.
There are quite a few other functions inside the $(document).ready function which I omitted due to clarity... but as far as the scope of where the if statement lies it is directly inside of the document.ready function. P.S. The form is shown and hidden dynamically, but it is hard coded -- it is not being created dynamically.
What is wrong with where I have this if statement located?
Try with .val() like
$(document).ready(function(){
if ($("input").val()) {
$("h1").hide();
}
});
Better you use either name or id or class names as selectors.Because input can be of any number and they also includes checkboxes,radio buttons and button types
In jQuery you have to use .val() method and not .value(). Your check should be as follows:
if ($("input").val()) {
$("h1").hide();
}
Unlike .value() in JS, ther's .val() in JQuery.
$(document).ready(function() {
if ($("input").value()) {
$("h1").hide();
}
});
You should use keyup to know when a key is added/removed from the textbox
$(document).ready(function() {
$("#input_data").keyup(function() {
var dInput = $(this).val();
alert(dInput);
});
});
DEMO
NOTE: Since input can be of any number and checkboxes, radio buttons and button types all are included within the HTML input tag, You should use either name or id or class names as **selectors**.
input[type=text]
or, to restrict to text inputs inside forms
form input[type=text]
or, to restrict further to a certain form, assuming it has id myForm
#myForm input[type=text]
If You want a multiple attribute selector
$("input[type='checkbox'][name='ProductCode']")
//assuming input type as checkbox and name of that input being ProductCode
.value() is invalid. You should use .val() instead of .value(). Hope it will make it work?
You should use val at the place of value and the solution is :
$(document).ready(function() {
if ($("input").val()) {
$("h1").hide();
}
});

Assign value to textbox

Hi i have a radio button(StarRating radiobutton using jquery) and a textbox. When i click on the star, i would like the radiobutton value to display to the textbox.
<input id="InsRating1" class="star" type="radio" name="InsRating" value="1" title="Worst"/>
<input id="InsRating2" class="star" type="radio" name="InsRating" value="2" title="Good"/>
I tried put the Onclick() in the but onClick() has never get fired.
Please advice how to get the value from my radiobutton to textbox. Thanks
I tried this below, but the value is "Undefined"
$(document).ready(function() {
$('#InsRating1').click(function() {
alert(this.value)
});
});
-------------Edit----------
I am using g_thom's answer below but come to this problem :
I have 3 set of stars with 3 textboxes. Each rating should show to only 1 textbox.
However whenever any star is clicked, it shows the value to all 3 textboxes instead of just specified one. Please advice. Thanks
<script type="text/javascript">
$(function() {
$('.star-rating').click(function() {
// assign the value of "total stars" to a textbox with an id of ratingText
$('#EvaluationInstructorRatingTextBox').val($('.star-rating-on').length);
});
$('.rating-cancel').click(function() {
// the value is '0' when the cancel button is clicked
$('#EvaluationInstructorRatingTextBox').val('0');
});
$('.star-rating').click(function() {
// assign the value of "total stars" to a textbox with an id of ratingText
$('#EvaluationMaterialRatingTextBox').val($('.star-rating-on').length);
});
$('.rating-cancel').click(function() {
// the value is '0' when the cancel button is clicked
$('#EvaluationMaterialRatingTextBox').val('0');
});
$('.star-rating').click(function() {
// assign the value of "total stars" to a textbox with an id of ratingText
$('#EvaluationValueRatingTextBox').val($('.star-rating-on').length);
});
$('.rating-cancel').click(function() {
// the value is '0' when the cancel button is clicked
$('#EvaluationValueRatingTextBox').val('0');
});
});
Since the inputs are converted to divs (with the 'rated stars' being assigned a different class), I think you'll want to count the number of divs with the .star-rating-on class and assign that value to the input, like this:
$('.star-rating').click(function() {
// assign the value of "total stars" to a textbox with an id of ratingText
$('#ratingText').val($('.star-rating-on').length);
});
Boring looking example - without the actual graphics/animations (just the HTML from the transformed inputs on plugin page - the value will always be 4): http://jsfiddle.net/bhf2d/
EDIT
The code above should work. I think you may be thinking that you need to apply your jQuery to the radio button, but that's not the case, since it is swapped out on page load with a div. Just in case you're not clear, I've added a live example using the code you provided in your question: Click here to see it.
EDIT 2
See an updated version here, matching the additional requirement to set multiple checkboxes. The textboxes have been renamed slightly (InsRatingText0 etc) to facilitate easily adding more items. The name convention InsRatingText[n] is set that way to match the div classes the plugin adds dynamically ('rater-0', 'rater-1', etc)
These <input> elements are not clicked, since they are hidden and replaced by <div> elements. You should use onChange() events instead.
Also, radio button do not use the property value, but checked.
Try something like this
$(function (){
$(".star").click(function(){
$("#textbox1").val($(this).val());
});
});
Basically, it is adding a handler for onclick to the eloement with class ="star" and then copying that value to the textbox.
$(".star").bind('click', function() {
$("#ratingValue").val($(this).text())
});
Seems like getting the val() on the checkbox didn't work, but using text() gives the value. Here is the example working: jsfiddle

call the input element through the value instead of id or name of the element in javascript method

i want to disable the textarea onclick of value=1 and enable it back by clicking of radio button value=0. however i have a condition that i have to use the same name and id for both the radio buttons.i have the existing code something like this ..is there is any possibilty that i can call the radio button through their values in js method.
HTML:
<input type="radio" name="disabilityflag" id="disabilityflag" value="0"/>
<span>Yes</span>
<input type="radio" name="disabilityflag" id="disabilityflag" value="1"/>
<span>No</span>
<textarea type="text" name="disabilityspecification" id="disabilityspecification">
</textarea>
Javascript:
$('#disabilityflag').click(function(){
checkeddisabilityclick();
});
function checkeddisabilityclick(){
$('#disabilityspecification').attr("disabled",true);
$('#disabilityspecification').addClass('disabled');
}
$('#disabilityflag').click(function(){
$('#disabilityspecification').removeAttr("disabled");
$('#disabilityspecification').removeClass('disabled');
});
if($('#disabilityflag').attr('checked')) {
checkeddisabilityclick();
}
You can use this.value property inside the event handler function.
$('#disabilityflag').click(function(){
alert( this.value) // will correspond to the value of the element that triggered the event.
checkeddisabilityclick();
});
Since you are using jquery, you can just do:
$('#disabilityflag[value="0"]').click(function () {
// Yes was clicked
});
$('#disabilityflag[value="1"]').click(function () {
// No was clicked
});
There's a running example here
Update:
I like Gunner's solution better because it only places one event handler but this would be how to do it if you only wanted an event handler on one of them.
The ID tag is supposed to be unique. Simply rename the IDs to disabilityflag_no and disabilityflag_yes and add two click events to them.
On the other hand you could do (replaced id with the name value)
$('[name="disabilityflag"]').click(function(){
alert( this.value) // will correspond to the value of the element that triggered the event.
checkeddisabilityclick();
});

Categories