JS/jQuery for assigning values - javascript

I am trying to achieve this:
Currently value has been set on 2 radio buttons.
Once one of the button is selected, the value(attribute) of that button should be assigned to the value of the div with an id.
I am not sure where I am going wrong. Below is the code snippet.
var init_font_one = $('input[id="init-one-name"]'),
init_font_two = $('input[id="init-two-name"]'),
init_id_value = $("#test");
if (init_font_one == 'checked') {
init_id_value.val(init_font_one.val());
}
if (init_font_two == 'checked') {
init_id_value.val(init_font_two.val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" value="abc"> Testing
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>

You have to use on('change' to update the value of div when radio button is click. And use attr of jQuery to update the value of particular element.
Try this.
var init_font_one = $('input[id="init-one-name"]'),
init_font_two = $('input[id="init-two-name"]'),
init_id_value = $("#test");
init_font_one.change(function() {
init_id_value.attr("value",init_font_one.val());
console.log(init_id_value.attr("value"));
});
init_font_two.on('change',function() {
init_id_value.attr("value",init_font_two.val());
console.log(init_id_value.attr("value"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>

There is few problems with your code:
<div> can't have value property.
Your code executes on page load and not when some event was triggered.
init_font_one == 'checked' compares jQuery object with string.
input[id="init-one-name"] can be replaced with #init-one-name
Your labels are not linked with inputs.
$('.radios').change(function() {
$("#test").val($('.radios:checked').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<!-- uncomment below -->
<!--<input type="hidden" id="test" value="abc"/>-->
<input type="text" id="test" value="abc" /> Testing
</div>
<input class="radios" id="init-one-name" type="radio" name="init-one-name" value="abcd"><label for="init-one-name">Test1</label>
<input class="radios" id="init-two-name" type="radio" name="init-one-name" value="xyz"><label for="init-two-name">Test2</label>

You should use jQuery change event to detect the change in the radio buttons and assign the value of checked radio button to the div with id="test"
var init_id_value = $("#test");
$('input[id="init-one-name"]').on('change', function() {
init_id_value.text($(this).val());
});
$('input[id="init-two-name"]').on('change', function() {
init_id_value.text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>

try this
$(document).ready(function(){
$("input[type='button']").click(function(){
var radioValue =
$("input[name='init-one-name']:checked").val();
if(radioValue){
alert("Your are a - " + radioValue);
}
});
});

I do not understand what you are trying to do, but try this:
$( "input[name='init-one-name']" ).change(function(){
$('#test').val('New Value: ' + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="test">Testing
</textarea><BR>
<input type="radio" name="init-one-name" value="abcd"><label>Op 1</label>
<input type="radio" name="init-one-name" value="xyz"><label>OP 2</label>

There is no value on a div, but you can change the text content or you can assing a "virtual value" to the div using .data()
Check the snippet
$(function(){ // On jquery initialize
var idtest = $('#test'); // the target Div
$('input[type="radio"]').on('change',function(){ // change event for the two radio buttons
/*** Method 1 : Using data attribute to assing a value ***/
idtest.data('value',$(this).val()); // Value of the selected radio
/*** Method 2 : Add the value of the selected radio to the text inside the div ***/
idtest.text( $(this).val() ) // Value of the selected radio
//retrieve the setted data value
console.log( idtest.data('value') );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>

Refer to the fixed code below.
Added a listener to detect action performed over the radio buttons and changed method to check if radio is checked or not.
let ele = document.getElementById('init-one-div');
ele.addEventListener('click', function(e) {
if ("INPUT" === e.target.nodeName)
checkAndAssign();
});
function checkAndAssign() {
var init_font_one = $('#init-one-name'),
init_font_two = $('#init-two-name'),
init_id_value = $("#test");
if (init_font_one.is(':checked')) {
init_id_value.val(init_font_one.val());
}
if (init_font_two.is(':checked')) {
init_id_value.val(init_font_two.val());
}
//REMOVE below line if you want to remove the line printing the result
init_id_value.html(' Testing [ ' + init_id_value.val() + ' ] ');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<div id="init-one-div">
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"> <label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"> <label>Test2</label>
</div>

Related

How to get Selected Checkbox value by ID

Currently my code works well with the input name, I can get the input value by input name
But I want my script to retrieve the input value with id input and not with name input?
here my code :
$(document).ready(function () {
$('input[type="checkbox"]').click(function () {
getSelectedCheckBoxwithValueText("test")
});
var getSelectedCheckBoxwithValueText = function (name1) {
var data = $('input[name="' + name1 + '"]:checked');
if (data.length > 0) {
var resultdata='' ;
data.each(function () {
var selectedValue = $(this).val();
resultdata += $('label[for="cb-' + selectedValue + '"]').text() + "<br/>";
});
$("#divchecked").html(resultdata);
}
else {
$("#divchecked").html("No Check box selected");
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
checked:
<input type="checkbox" id="c1" name="test" value="cricket" />
<label for="cb-cricket">Cricket</label>
<input type="checkbox" id="c2" name="test" value="swimming" />
<label for="cb-swimming">Swimming</label>
<input type="checkbox" id="c3" name="test" value="blog" />
<label for="cb-blog">Blog</label>
<input type="checkbox" id="c4" name="test" value="coding" />
<label for="cb-coding">Coding</label>
<br/>
<br/>
Selected checkbox:<br />
<div id="divchecked"></div>
</body>
jsfiddle: https://jsfiddle.net/showcode/L64nauo0/5/
You can use
var data = $('input[id=^"c"]:checked');
Only if the IDs not pseudos (so you really this IDs use), and do not use IDs thagt starts with c
This is a little hacker solution, but works!
There is no need to use id or name to select the checkboxes and/or their related labels. You can simplify your code like so
Select all the checkboxes from the DOM and listen to change event on them.
When the value of a checkbox changes, you get all selected checkboxes
using .filter().
And then get the text of the related labels using .map() and .get().
$(document).ready(function () {
let $checkboxes = $('input[type="checkbox"]');
$checkboxes.change(function () {
let labels = $checkboxes.filter(':checked').map(function(){
return $(this).next('label').text().trim();
}).get();
$("#divchecked").html(labels.join('<br />') || "No Check box selected");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
checked:
<input type="checkbox" id="c1" name="test" value="cricket" />
<label for="c1">Cricket</label>
<input type="checkbox" id="c2" name="test" value="swimming" />
<label for="c2">Swimming</label>
<input type="checkbox" id="c3" name="test" value="blog" />
<label for="c3">Blog</label>
<input type="checkbox" id="c4" name="test" value="coding" />
<label for="c4">Coding</label>
<br/>
<br/>
Selected checkbox:<br />
<div id="divchecked"></div>

Get the value of a radio button using jquery [duplicate]

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)

how to hide and show named divs according to radio value?

This one is quite similar to my other question on:
how to hide and show named divs according to enum value?
Idea here is slightly different, though. The toggle() jQuery function is related to a radio button which is coded below:
<div id="recurrent">
<label for="recurrent">Recurrent? </label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
The div to toggle is:
<div id="ifRecurrentTrue">
/// something
</div>
And the adapted jQuery from the other question is:
$('#recurrent select').on('change', function () {
var value = this.value;
$('#ifRecurrentTrue').toggle(value == true);
}).change();
I bet it's just a matter of different functions, right?
Again, thanks in advance!
You need to find the input elemetns by its name, so use the attribute equals selector instead of the element selector select
$('#recurrent input[name="recurrent"]').on('change', function() {
$('#ifRecurrentTrue').toggle(this.checked && this.id == 'idtrue');
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="recurrent">
<label for="recurrent">Recurrent?</label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
<div id="ifRecurrentTrue">
/// something
</div>
Did't see the element with select tag on provided code, could be input. Replace select with input like following:
$('#recurrent input').on('change', function () {
var value = this.value;
$('#ifRecurrentTrue').toggle(value == true);
}).change();
$(document).ready(function() {
$('input:radio[name=recurrent]').on('change', function () {
var values = this.value;
$('#ifRecurrentTrue').toggle(values =='true');
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="recurrent">
<label for="recurrent">Recurrent? </label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
<div id="ifRecurrentTrue">
/// something
</div>

How can I set html radio value from javascript?

How can I set html radio value from javascript ??
I try this code
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$.getJSON("getquestion.php",function(result)
{
//set radio value
//$("#choice").html(result.test_choice_a);
//$("#choice").val(result.test_choice_a);
//$("#choice").html(result.test_choice_b);
//$("#choice").val(result.test_choice_b);
//$("#choice").html(result.test_choice_c);
//$("#choice").val(result.test_choice_c);
//$("#choice").html(result.test_choice_d);
//$("#choice").val(result.test_choice_d);
document.testform.choice[0].value = result.test_choice_a;
document.testform.choice[1].value = result.test_choice_b;
document.testform.choice[2].value = result.test_choice_c;
document.testform.choice[3].value = result.test_choice_d;
}
</script>
<input type="radio" name="choice" id="choice" ><br>
<input type="radio" name="choice" id="choice"><br>
<input type="radio" name="choice" id="choice"><br>
<input type="radio" name="choice" id="choice"><br>
but it didn't work.
How can I set it ?? help me please.
Maybe the content hasn't loaded yet put your ajax call in a $(document).ready()
$(document).ready(function(){
$.getJSON("getquestion.php",function(result)
{
//set radio value
//$("#choice").html(result.test_choice_a);
//$("#choice").val(result.test_choice_a);
//$("#choice").html(result.test_choice_b);
//$("#choice").val(result.test_choice_b);
//$("#choice").html(result.test_choice_c);
//$("#choice").val(result.test_choice_c);
//$("#choice").html(result.test_choice_d);
//$("#choice").val(result.test_choice_d);
document.testform.choice[0].value = result.test_choice_a;
document.testform.choice[1].value = result.test_choice_b;
document.testform.choice[2].value = result.test_choice_c;
document.testform.choice[3].value = result.test_choice_d;
});
});
Also element ids should be unique.
You need to give every radio a uniquie id.
<script type="text/javascript">
$.getJSON("getquestion.php",function(result) {
//set radio value
$("#choice_1").val(result.test_choice_a);
$("#choice_2").val(result.test_choice_b);
$("#choice_3").val(result.test_choice_c);
$("#choice_4").val(result.test_choice_d);
}
</script>
<input type="radio" name="choice" id="choice_1" ><br>
<input type="radio" name="choice" id="choice_2"><br>
<input type="radio" name="choice" id="choice_3"><br>
<input type="radio" name="choice" id="choice_4"><br>
You can't give an id to many elements
$(document).ready(function () {
$.getJSON("getquestion.php", function (result) {
$("#choice_1").val(result.test_choice_a);
$("#choice_2").val(result.test_choice_b);
$("#choice_3").val(result.test_choice_c);
$("#choice_4").val(result.test_choice_d);
});
});

make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle

Categories

Resources