How to get Selected Checkbox value by ID - javascript

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>

Related

Need help on Checkbox onclick jquery

trying to learn jquery and made a simple checkbox with a function where you can make all the options read-only checking on "none of the above" button.
<html>
<body>
<form id="diagnosedForm">
<div>
<input type="checkbox" value="1"/>1
<br/>
<input type="checkbox" value="2"/>2
<br/>
<input type="checkbox" value="3"/>3
<br/>
</form><br/>
<input type="checkbox" value="" onclick="enableDisableAll(this);"/>None of the above
<script src="script.js">
</script>
</body>
</html>
function enableDisableAll(e) {
var own = e;
var form = document.getElementById("diagnosedForm");
var elements = form.elements;
for (var i = 0 ; i < elements.length ; i++) {
if(own !== elements[i] ){
if(own.checked == true){
elements[i].disabled = true;
elements[i].checked = false;
}else{
elements[i].disabled = false;
}
}
}
}
this will be the output
and the last checkbox will make it read-only
I want the same result but not putting onclick on the html file, instead using jquery to work it out.
You can assign an id to "none of the above" checkbox and then in your script.js you can do something like this:
// script.js
// Run enableDisableAll() on toggle click
$('#toggle').click(enableDisableAll)
function enableDisableAll() {
// Find all input elements inside "diagnosedForm"
const elements = $('#diagnosedForm input')
// Map thru inputs and toggle enable/disable state
elements.map((_, el) => {
$(el).prop('checked', false) // Reset checkboxes
$(el).prop('disabled', (i, v) => !v)
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form id="diagnosedForm">
<div>
<input type="checkbox" value="1" />1
<br/>
<input type="checkbox" value="2" />2
<br/>
<input type="checkbox" value="3" />3
<br/>
</div>
</form>
<br/>
<input id="toggle" type="checkbox" value="" /> None of the above
</body>
</html>

JS/jQuery for assigning values

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>

How to get all checkbox values and put value of each one to a specific text input

I have a checkbox with (20) choices and also (20) input fields , i need : when user choose one or more option, put value of checked checkbox in a separate input field else put (0)
I tried the following and it working when user chose only one option.
$(".cont").change(function() {
if($('.cont :checked').val() == "1") {
$('#q1').val('1');
}else{
$('#q1').val('0');
}
if($('.cont :checked').val() == "2") {
$('#q2').val('2');
}else{
$('#q2').val('0');
}
if($('.cont :checked').val() == "3") {
$('#q1').val('3');
}else{
$('#q3').val('0');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
</div>
<input id="q1" type="text" >
<input id="q2" type="text" >
<input id="q3" type="text" >
You can combine the uses of .val() and .is(':checked').
$('#q' + $(this).val()) will select the correct text input.
$(this).is(':checked') ? $(this).val() : 0 will put your checkbox value inside your input if checked, 0 if not.
$('.cont input[type="checkbox"]').change(function() {
$('#q' + $(this).val()).val($(this).is(':checked') ? $(this).val() : 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
</div>
<input id="q1" type="text">
<input id="q2" type="text">
<input id="q3" type="text">
You need to follow these steps and use much more managed code to achieve this:
Detect change on checkbox checked/unchecked
Get the value of the checkbox and since the id of the input element
is prefixed with q and the value of the checkbox, get the id
first
Use this id to fill the value in the input element.
In addition, you can check for uncheck of the checkbox and substitute
the previous value with null.
$('input[type="checkbox"]').change(function() {
var checkedValue = $(this).val();
var inputElemId = "q"+checkedValue;
if($(this).is(':checked')){
$('#'+inputElemId).val(checkedValue);
} else {
$('#'+inputElemId).val(null);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
</div>
<input id="q1" type="text" >
<input id="q2" type="text" >
<input id="q3" type="text" >

Get Elements of Certain Type within a Div with jQuery

I have an HTML page that is dynamically generated. A rough version of the HTML looks like this:
<div id="brotherDiv">
<input type="radio" name="myOtherGroup" value="A" />
<input type="radio" name="myOtherGroup" value="B" />
</div>
<div id="myDiv">
<input type="radio" name="myGroup" value="1"></input>
<input type="text" id="myText" name="myText"></input><br />
<input type="radio" name="myGroup" value="2"></input>
<input type="text" id="myText2" name="myText2"></input><br />
<input type="radio" name="myGroup" value="3"></input><br />
<input type="radio" name="myGroup" value="4"></input>
</div>
<div id="sisterDiv"></div>
I am trying to
Get all of the radio buttons in myDiv
Get the index of the selected radio button in the result of #1.
Is there a way to do this type of query in jQuery? If so, how? Currently, I have
var rbs = $("input[name='myGroup']");
I feel like I'm close.
I'd suggest:
var rbs = $("#myDiv input[name='myGroup']:checked"),
index = rbs.index(),
// amongst its siblings, or:
inputIndex = rbs.index('input[name="myGroup"]');
// amongst other input elements of the same group
References:
CSS:
Attribute presence and value selectors.
:checked pseudo-class.
jQuery:
index().
var rbs = $('#myDiv input[type="radio"]'); // Get radio buttons
var result = $('#myDiv input[type="radio"]:checked') // Get checked radio buttons
All radio buttons in #myDiv:
var rbs = $('#myDiv :radio');
Checked:
var checkedIndex = rbs.filter(':checked').index(':radio');
Answer to #1:
var radios = $('#myDiv input[type="radio"][name="myGroup"]');
Answer to #2:
var checkedRadios = radios.index( $('#myDiv input[type="radio"][name="myGroup"]:checked') );
Try
var rbs = $("#myDiv [type=radio]") // #1
, rbschecked = null; // #2 , pending change event
rbs.change(function(e) {
rbschecked = rbs.index(e.target) // #2
})
var rbs = $("#myDiv [type=radio]")
, rbschecked = null;
rbs.change(function(e) {
rbschecked = rbs.index(e.target);
e.target.dataset.i = rbschecked;
console.log(rbschecked)
})
#myDiv input:checked:after {
position : relative;
content : attr(data-i);
left : 12px;
top : -2px;
color : blue;
font-family : arial;
font-style : italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="brotherDiv">
<input type="radio" name="myOtherGroup" value="A" />
<input type="radio" name="myOtherGroup" value="B" />
</div>
<div id="myDiv">
<input type="radio" name="myGroup" value="1"></input>
<input type="text" id="myText" name="myText"></input><br />
<input type="radio" name="myGroup" value="2"></input>
<input type="text" id="myText2" name="myText2"></input><br />
<input type="radio" name="myGroup" value="3"></input><br />
<input type="radio" name="myGroup" value="4"></input>
</div>
<div id="sisterDiv"></div>

Pass all checkboxes values as an array in Javascript

I have the below checkboxes and I need to get them as an array values.
<input type="checkbox" id="contact_id" value="4" />
<input type="checkbox" id="contact_id" value="3" />
<input type="checkbox" id="contact_id" value="1" />
<input type="checkbox" id="contact_id" value="5" />
I need to pass them to one ajax request as array as below:
xmlHttp.open("POST","?action=contact&contact_id=" +contacts,true);
I am using this function to get the values but not able to pass them to the function as array, the passed like this 4,3,1,5. I need them to be passed like this
contact_id[]=4&contact_id[]=3&contact_id[]=1&contact_id[]=5
I have done this as follows
function getContacts(){
var contacts = document.myform.contact_id, ids = [];
for (var i = 0; i < contacts.length; i += 1){
if (contacts[i].checked)
ids.push(contacts[i].value);
}
return ids;
}
http://jsfiddle.net/xQezt/
Does this fiddle do what you want? The serialization is naive, but you could find a proper way to do that exact thing elsewhere or by using a framework like Zepto, jQuery or YUI.
First I made a way to "submit" the data. The output goes to the console, so open your firebug. Could go anywhere, though.
//submit event registration
submitButton.onclick = function () {
var contactArray = inputsToArray(contacts.children);
var data = serializeArray(contactArray, 'contact_id[]');
console.log(data);
}
Then I made your method "getContacts" more generic:
function inputsToArray (inputs) {
var arr = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
arr.push(inputs[i].value);
}
return arr;
}
Here is the naive serialization function. I do not expect this to work well in all cases, so you should do some research in where to get a good serialization algo from:
function serializeArray (array, name) {
var serialized = '';
for(var i = 0, j = array.length; i < j; i++) {
if(i>0) serialized += '&';
serialized += name + '=' + array[i];
}
return serialized;
}
I also slightly modified your HTML:
<div id="contacts">
<input type="checkbox" value="4" />
<input type="checkbox" value="3" />
<input type="checkbox" value="1" />
<input type="checkbox" value="5" />
</div>
<button id="submit">Submit</button>
Which let me query the DOM like this:
var d=document;
var submitButton = d.getElementById('submit');
var contacts = d.getElementById('contacts');
Your input's id are duplicate. so I recommend you to use name instead of id
For Example, Your HTML will look like this :
<form id='contactform'>
<input type="checkbox" name="contact[]" value="4" />
<input type="checkbox" name="contact[]" value="3" />
<input type="checkbox" name="contact[]" value="1" />
<input type="checkbox" name="contact[]" value="5" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Then if you want to get the value to querystring then use the JQuery Serialize
$('#contactform').serialize();
// this will take some thing like this, Example check the second and the fourth
// contact%5B%5D=3&contact%5B%5D=5
jsFiddle : http://jsfiddle.net/Eqb7f/
$(document).ready(function() {
$("#submit").click(function(){
var favorite = [];
$.each($("input[class='check']:checked"), function(){
favorite.push($(this).val());
});
document.getElementById('fav').value = favorite.join(", ");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cd-form-list">
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="A">
<label for="cd-checkbox-1">A for Apple</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="B">
<label for="cd-checkbox-2">B for Ball</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-3" class="check" value="C">
<label for="cd-checkbox-3">C for Cat</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-4" class="check" value="D">
<label for="cd-checkbox-4">D for Dog</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-5" class="check" value="E">
<label for="cd-checkbox-5">E for Ear</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-6" class="check" value="F">
<label for="cd-checkbox-6">F for Fish</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-7" class="check" value="G">
<label for="cd-checkbox-7">G for God</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-8" class="check" value="H">
<label for="cd-checkbox-8">H for Hen</label>
</div>
</div>
<div>
<input type="submit" value="Submit" id="submit">
</div>
<input name="services" id="fav">

Categories

Resources