How to get the value field of HTML Control in Javascript?
Instead of picking the Id , I am trying to get the value which is 4875.
<input data-val="true" data-val-required="Required" id="ChangesInTreatYes" name="ChangesInTreat" type="radio" value="4875" /> Yes
<input id="ChangesInTreatNo" name="ChangesInTreat" type="radio" value="4876" /> No
if ($("input:radio[name='ChangesInTreat']:checked").length > 0) {
var isChecked1 = document.getElementById("ChangesInTreatYes").checked;
alert(isChecked1);
}
jQuery makes it simple -- for nearly all form elements, .val() will return the value of the element.
let toggleEl = $("input[name='ChangesInTreat']")
toggleEl.on("change", function(){
console.log($(this).val() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-val="true" data-val-required="Required" id="ChangesInTreatYes" name="ChangesInTreat" type="radio" value="4875" /> Yes
<input id="ChangesInTreatNo" name="ChangesInTreat" type="radio" value="4876" /> No
To do the same thing with plain old javascript:
let toggleEl = document.querySelectorAll("input[name='ChangesInTreat']")
// Go over each radio button, and add an event handler
toggleEl.forEach(function(element){
element.addEventListener("change", function(){
console.log(this.value)
})
})
<input data-val="true" data-val-required="Required" id="ChangesInTreatYes" name="ChangesInTreat" type="radio" value="4875" /> Yes
<input id="ChangesInTreatNo" name="ChangesInTreat" type="radio" value="4876" /> No
FYI, you are intermixing jQuery and javascript. Would suggest choosing one type and sticking with it.
Get value of radio using javascript by name:
var isChecked1 = document.querySelector("input[name='ChangesInTreat']:checked").value;
Get value of radio using jQuery by name:
var isChecked1 = $("input[name='ChangesInTreat']:checked").val();
Related
I have some multiple radio buttons on a page with a different id. Depending on the choosen value a upload button or a textbox must show up. But because it's 10 times almost the same code (the only difference is a number) I was looking for a solution where I can reuse the code.
Example of two radio groeps:
<input type="radio" name="typePhoto2" id="foto2" value="photo">
<input type="radio" name="typePhoto2" id="video2" value="video">
<input type="radio" name="typePhoto3" id="foto3" value="photo">
<input type="radio" name="typePhoto3" id="video3" value="video">
I known there is a way to use jQuery with a * to select multiple elements, but what I want is to use the value of '*' to provide which number is choosen.
$("[id^=typePhoto]").click(function(){
var value = [number after the id];
})
Is there a way to do this? Otherwise I have to copy paste 10 times the same code with only a number as difference.
You can always reach the id of the current target through the event object,
and then with a little regex you're done:
$("[id^='foto']").click(function(e){
var id = e.currentTarget.id
var value = id.match(/[0-9]$/)[0];
console.log(value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="typePhoto2" id="foto2" value="photo">
<input type="radio" name="typePhoto3" id="foto3" value="photo">
You need to fix the selector to target all element with name attribute value starts with typePhoto .then get the current id using clicked element context this and remove static part using .replace():
$("[name^=typePhoto]").click(function(){
var value = this.id.replace("foto","").replace("video","");
});
Working Snippet :
$("[name^=typePhoto]").click(function(){
var value = this.id.replace("foto","").replace("video","");
console.log(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="typePhoto2" id="foto2" value="photo">
<input type="radio" name="typePhoto2" id="video2" value="video">
<input type="radio" name="typePhoto3" id="foto3" value="photo">
<input type="radio" name="typePhoto3" id="video3" value="video">
You could try:
$('[id*="typePhoto"]')
or
$('input[type="radio"]');
Cheers
A better way to do that would be to give them all the same class. For instance class="photo-button". then you could use:
$(".photo-button").click(function(){...})
Try like this
$( "input[name*='typePhoto']" ).click( function(){
// your code
});
This question already has answers here:
How to check a radio button with jQuery?
(33 answers)
Closed 6 years ago.
I have this portion of code:
var checkout_options = $("#checkout").find("input[type='radio']");
$('#button-account').on('click', function () {
alert(checkout_options.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
<input type="button" value="Continue" id="button-account">
</div>
What I want it is to get the value of the selected radio button but with my code I only get the first radio button value, the second radio does not work.
Kindly help me fix the error.
You need to use this to refer the element inside the callback. So get value by using this.value or $(this).val() method. Although avoid :checked pseudo-class selector otherwise it only selects the first element.
var selected = $("#checkout").find("input[type='radio']");
selected.change(function(){
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>
You can make it simpler using :radio pseudo-class selector
$("#checkout :radio").change(function() {
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b>
</label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>
Your handler is only being attached to the radio button that is checked, so no handler exists for the second radio button. Attach a handler to both radio buttons:
var $radioBtn = $( "#checkout" ).find( "input[type='radio']" );
$radioBtn.on( 'change', function() {
if ( this.checked ) {
alert( this.value );
}
});
It didn't work, because you register the event handler for the initially checked value only. This is how to make it dynamically reflect the value change:
var selected = $("#checkout").find("input[name='account']");
selected.change(function(){
alert($(this).val());
});
This also makes sure that only the current radio button group is included, so you can have additional ones.
Jsfiddle:
https://jsfiddle.net/sjmhdasw/
Just use
$("input[type='radio']").on("change", function() {
console.log(this.id + " checked !");
});
It binds an event listener on all the inputs of type radio !
No need to store the selectors inside a variable (unless you're doing something with it, somewhere else in your code)
Is there any way I can have a user check a box and it automatically adds a number 1 in a corresponding number box? This is what I have so far, but it's not adding a number into the box when I check it. Where am I going wrong?
$(document).ready(function () {
$(".copyMe").keyup(function () {
$(".copyMe").val($(this).val());
});
});
<input class="copyMe" type="checkbox" />
<input class="copyMe" type="number" />
Is this what you're after? (Jsfiddle)
<input class="copyMeCheckbox" type="checkbox" />
<input class="copyMeNumber" type="number" />
$('.copyMeCheckbox').on('change',function(){
$('.copyMeNumber').val(1);
});
The problem is you have to differentiate between the check box and the number input. (EDIT: note that you can do this without changing the class, but I've done that here to be more specific in naming the elements). If you want to make the number input "1" when the box is checked, you have to have a handler on the checkbox. fiddle here: http://jsfiddle.net/h42j0ph3/1/
<div class="checkbox-number-container">
<input class="check-box" type="checkbox" />
<input class="number-input" type="number" value="0" />
</div>
$(".checkbox-number-container .check-box").on('click', function () {
var $checkbox = $(this);
var $numberInput = $checkbox.parent('.checkbox-number-container').find('.number-input');
if($checkbox.is(':checked')){
$numberInput.val(1);
}
else{
$numberInput.val(0);
}
});
Provided that you love to keep your markup at it is, here's you can do to make it work :
<input class="copyMe" type="checkbox" />
<input class="copyMe" type="number" />
$(document).ready(function () {
$("input:checkbox[class='copyMe']").on("change",function ()
{
$("input[type='number'][class='copyMe']").val('1');
});
});
Jsfiddle : https://jsfiddle.net/s4unjx41/1/
I have this form
<form id=my_form>
<input id=mt type=text><input id=mc type=checkbox><textarea id=mta />
</form>
I want to have a button somewhere else, that can serialize the form WITH its state, that is, if the textarea has a content, or the text has a content or the checkbox is pressed, I want that information to be stored somehow in the string. Later, I would like to restore the information in the form using that string.
I tried with .innerHTML and it didn't work, I always got the original HTML.
I also looked at the serialize method of jQuery, but I was not able to deserialize it "inside" the form.
Thank you in advance!
Kurt
I've made examples for you. Tested - working fine.
You need jQuery library
First here goes the form:
<form id="my_form">
<input id="formText" type="text" name="formText" />
<br />
<label><input id="formCheck" type="checkbox" name="formCheck" /> check 1</label>
<br />
<label><input id="formCheck2" type="checkbox" name="formCheck2" /> check 2</label>
<br />
<textarea name="formTextarea" id="formTextarea" cols="20" rows="3"></textarea>
<br />
<label><strong>Time unit</strong>:</label>
<p>
<label><input type="radio" name="dataView" value="week" checked="checked" /> Week</label>
<label><input type="radio" name="dataView" value="month" /> Month</label>
<label><input type="radio" name="dataView" value="year" /> Year</label>
</p>
<input type="button" value="Serialize" onclick="serializeForm()" />
<input type="button" value="Unserialize" onclick="restoreForm()" />
</form>
After clicking buttons, corresponding function are called in js
And here is the js:
Serialized data is stored in formData variable, and if needed you can store it in cookie, in database etc... And later load it, regarding your requirements
<script type="text/javascript">
var formData;
function serializeForm() {
formData = $('#my_form').serialize();
}
function restoreForm() {
var obj = unserializeFormData(formData);
// Restore items one by one
if(obj.hasOwnProperty('formTextarea')) {
$('#formTextarea').val(obj.formTextarea);
}
if(obj.hasOwnProperty('formText')) {
$('#formText').val(obj.formText);
}
// Radio buttons
if(obj.hasOwnProperty('dataView'))
$('input[value="'+obj.dataView+'"]').attr('checked', true);
// Restore all checkbox. You can also iterate all text fields and textareas together, because the have same principle for getting and setting values by jQuery
$('#my_form input[type="checkbox"]').each(function(){
var checkName = $(this).attr('name');
var isChecked = false;
if(obj.hasOwnProperty(checkName))
isChecked = true;
$(this).attr('checked',isChecked);
});
}
function unserializeFormData(data) {
var objs = [], temp;
var temps = data.split('&');
for(var i = 0; i < temps.length; i++){
temp = temps[i].split('=');
objs.push(temp[0]);
objs[temp[0]] = temp[1];
}
return objs;
}
</script>
Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
var firstPrice = $25
var secondPrice = $56
var thirdPrice = $80
var fourthPrice = $90
then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)
My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:
<label>
<input type="radio" name="model" value="radio" id="item_0" />
item 1</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_1" />
item2</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_2" />
item3</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_3" />
Item4</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_4" />
item5</label>
</form>
then my script looks something like:
function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;
var totalPrice = (selectionFirst + selectionSecond + selectionThird + selectionFourth);
}
Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/
Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.
Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.
<script type="text/javascript">
//function updatePrice(el) {
function updatePrice(event) {
var el = event.target || event.srcElement;
var form = el.form;
if (!form) return;
var control, controls = form.elements;
var totalPrice = 0;
var radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if ((control.type == 'radio' || control.type == 'checkbox') && control.checked) {
totalPrice += Number(control.value);
}
// Deal with other types of controls if necessary
}
form.totalPrice.value = '$' + totalPrice;
}
</script>
<form>
<fieldset><legend>Model 1</legend>
<input type="radio" name="model1" value="25">$25<br>
<input type="radio" name="model1" value="35">$35<br>
<input type="radio" name="model1" value="45">$45<br>
<input type="radio" name="model1" value="55">$55<br>
</fieldset>
<fieldset><legend>Model 2</legend>
<input type="radio" name="model2" value="1">$1<br>
<input type="radio" name="model2" value="2">$2<br>
<input type="radio" name="model2" value="3">$3<br>
<input type="radio" name="model2" value="4">$4<br>
<fieldset><legend>Include shipping?</legend>
<span>$5</span><input type="checkbox" value="5" name="shipping"><br>
</fieldset>
<input name="totalPrice" readonly><br>
<input type="reset" value="Clear form">
</form>
You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.