document.forms checkbox value [duplicate] - javascript

This question already has answers here:
Get the value of checked checkbox?
(15 answers)
Closed 5 years ago.
I have a form and I want to get which checkbox is selected in plain JS and get its value returned. I get it with radio buttons but not with checkbox and just cant figure out how should it be called if I call it the same as with radio buttons it returns empty string code below.
Example with radio buttons:
/*html*/
<input type="radio" name="q5" value="a" id="q5a">a. test1<br>
<input type="radio" name="q5" value="b" id="q5b">b. test2<br>
/*js, gets the value which is selected either a or b as per html*/
var q5 = document.forms["quizForm"]["q5"].value;
Now I try this with checkboxes:
/*html*/
<input type="checkbox" name="q6" value="c" id="q6c">c. test1<br>
<input type="checkbox" name="q6" value="d" id="q6d">d. test2<br>
/*js returns an empty string "" when either checked or both*/
var q6 = document.forms["quizForm"]["q6"].value;

Checkbox behavior is different from the radio.
var checkedValue = null;
var inputElements = document.getElementsByName('q6');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
got from

It should actually be:
document.forms["quizForm"]["q5"].checked
And your form should have a name or an id equal to "quizForm" e.g. <form name="quizForm" ...> or <form id="quizForm" ...>

Related

Remove specific characters from string jquery [duplicate]

This question already has answers here:
jQuery: Add values of checkboxes to input text field
(4 answers)
Closed 4 years ago.
OK, So although it seems normal substring or replaces solution answer it is quite complex for me.
I have 3 checkboxes
A,B,C
and one text box
Now, when user select any checkbox the value of checkbox appends into textbox i.e. Fist he selects A -> textbox will be appended by A
Then if selects B -> textbox value will be A, B and so on.
i have done it already.
Now the problem is for unchecking.
If the value of textbox is A,B,C i.e. the selected checkboxes are A,B,C and if user deselects the B then the value should be A,C and then again deselects the c then the value should be A.
I have tried multiple ways but don't work for all conditions, sometimes it becomes A, C or A, B
Any solution?
Thank you in advance :)
You can simply recreate the list on change of a box
let els = [...document.getElementsByClassName('check')];
els.forEach(e => e.addEventListener('change', () => {
document.getElementById('foo').value = els.filter(x => x.checked).map(x => x.value).join();
}))
.flex {
display: flex;
flex-direction: column;
}
<div class="flex">
<input id="foo" />
<label><input type="checkbox" class="check" value="A"/>A</label>
<label><input type="checkbox" class="check" value="B"/>B</label>
<label><input type="checkbox" class="check" value="C"/>C</label>
</div>
Try this:
1) On each checkbox click/unclick get the value of all checked checkboxes. (for example ['A', 'B'])
2) Generate the new string with join the values . ['A', 'B'].join(',') // returns 'A,B'
3) Set the textbox with the new string
If you need code you can submit your current code.
Here's what I came up with, without knowing how you're tracking what's checked or not, it's a data driven approach.
var checked = [];
function updateValue() {
$('#selected').val(checked.toString());
}
$('[type=checkbox]').click(function(e) {
var value = e.target.value;
if(e.target.checked) {
checked.push(value);
} else {
checked.splice(checked.indexOf(value), 1);
}
updateValue();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="A">A<br>
<input type="checkbox" value="B">B<br>
<input type="checkbox" value="C">C<br>
<input type="text" id="selected">
$(function() {
const valArray = []; // our value array here what gonna show in textarea
/**
- on change check if checkbox checked or not
- if checked push value of checkbox to array
if not search in our array "valArray" and get it's index then remove it
- change textarea value with the new array "valArray"
*/
$('.checkboxes input').on('change', function(e) {
const $thisVal = $(this).val(),
isChecked = $(this).is(':checked');
if (isChecked) {
valArray.push($thisVal);
} else {
const searchOnThisVal = valArray.find(item => $thisVal === item),
getTheIdx = valArray.indexOf(searchOnThisVal);
valArray.splice(getTheIdx, 1);
}
$('.textarea').empty();
$('.textarea').text(valArray);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkboxes">
<label>
<input type="checkbox" value="a">
the checkbox A.
</label>
<label>
<input type="checkbox" value="b">
the checkbox B.
</label>
<label>
<input type="checkbox" value="c">
the checkbox C.
</label>
</div>
<textarea class="textarea" placeholder="your choice..."></textarea>
this should work in your case using jQuery API

How to get just selected value from the group of elements with the same name? [duplicate]

This question already has answers here:
How can I know which radio button is selected via jQuery?
(40 answers)
Closed 7 years ago.
I have two radio buttons with the same name but different values. I have to check before I submit my form that value selected id correct otherwise give message to user.
Here is my HTML code:
<td>
<label>
<span><input type="radio" name="directed" value="1" id="directed_yes"></span>
<span>Yes</span>
</label><br>
<label>
<span><input type="radio" name="directed" value="0" id="directed_no"></span>
<span>No</span>
</label>
</td>
Here is my JQuery that i tried to use:
var directed = $('input[name=directed]').each(function(){
alert($(this).val())
});
This code gave me all values for elements with the same name, I just need selected value. After that I have to check if that value is valid before submitting the form. If anyone know how to get just selected value please let me know. Thanks.
You can just use the :checked selector and val(): like this:
var directed = $('input[name=directed]:checked').val();
$('button').click(function() {
var directed = $('input[name=directed]:checked').val();
alert(directed);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<span><input type="radio" name="directed" value="1" id="directed_yes"></span>
<span>Yes</span>
</label>
<br>
<label>
<span><input type="radio" name="directed" value="0" id="directed_no"></span>
<span>No</span>
</label>
<br /><br />
<button>Get value</button>

How to get the text of the checked radio button? [duplicate]

This question already has answers here:
How do I get the label of the selected radio button using javascript
(3 answers)
Closed 8 years ago.
I have a group of radio buttons and want to get the checked radio button, then alert the text, not only the value of it. To explain more, when the user clicks the first radio button, and then submits the form, I want the browser to alert "Desktop Case." And I want to achieve this without jQuery.
<form action="" name="form1">
<label for="radio400">Desktop Case</label>
<input type="radio" name="rad_case" value="400" id="radio400"/>
<label for="radio401">Mini Tower</label>
<input type="radio" name="rad_case" value="401" id="radio401"/>
<label for="radio402">Full Tower</label>
<input type="radio" name="rad_case" value="402" id="radio402"/>
<input type="button" value="Submit" name="btn_submit" onclick="update_order_onclick()"/>
</form>
The following works for your example. It uses CSS selectors to target the checked input. Based on its id, the appropriate label is found:
function update_order_onclick() {
var value= 'Nothing selected',
selected= document.querySelector('input[name="rad_case"]:checked'),
selection= document.querySelector('#selection');
if(selected) {
value= document.querySelector('label[for="'+selected.id+'"]').innerHTML;
}
selection.innerHTML= value;
}
<form action="" name="form1">
<label for="radio400">Desktop Case</label>
<input type="radio" name="rad_case" value="400" id="radio400"/>
<br>
<label for="radio401">Mini Tower</label>
<input type="radio" name="rad_case" value="401" id="radio401"/>
<br>
<label for="radio402">Full Tower</label>
<input type="radio" name="rad_case" value="402" id="radio402"/>
<br>
<input type="button" value="Submit" name="btn_submit" onclick="update_order_onclick()"/>
</form>
<div id="selection"></div>
First, we create a function to loop through the radio buttons group we have, and checks if it is checked or not.
function get_radio_val(form, name)
{
var val;
var radios = form.elements[name];
for (var i =0; i < radios.length; i++)
{
if (radios[i].checked)
{
val = radios[i];
break;
}
}
return val;
}
Then we write the function that will be executed on onclick event.
function update_order_onclick()
{
var val = get_radio_val(document.form1, 'rad_case');
var val_id = val.id;
var selector = 'label[for=' + val_id + ']';
var label = document.querySelector(selector);
var label_text = label.innerHTML;
alert(label_text);
}
The thing that helped us here, is that the label for attribute has to be the same value as the radio button id and that's how we selected it in the function above.
simply do the following:
var checked = document.querySelector('input:checked');
var id = checked?checked.id:'bla';
var lab = document.querySelector('label[for='+id+']');
var lab_text = lab?lab.textContent:'';

Onchange on radio button not working in ie7/8 [duplicate]

This question already has answers here:
IE8 & IE7 onchange event is triggered only after repeated selection
(3 answers)
Closed 8 years ago.
I have few radio buttons. On click at any radio button different function calls. I don't want to call the function if radio button is already checked. To do that i used 'onchange' attribute on radio elements. But the problem is that it doesn't work in ie7. it work when it looses the focus. Is there any alternate or solution for this. i can't use jquery as well.
<input type="radio" onchange="test1()"/>A
<input type="radio" onchange="test2()"/>B
<input type="radio" onchange="test3()"/>C
<input type="radio" onchange="test4()"/>D
Try this one, check output in console (F12),
you can add all function to this code
<form name="myForm">
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
<input type="radio" name="myRadios" value="3" />
</form>
<script>
var rad = document.myForm.myRadios;
var prev = null;
for(var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log('previous - ' + prev.value):null;
if(this !== prev) {
prev = this;
}
console.log('current - ' + this.value)
};
}
</script>
Change it to onclick event and it should work as you wish.

ajax : how to get value of ratiogroup element

i have 3 elemests of radio group.
How can i get the value of the radio element?
can i have same id for all 3 elements?
??<input type="radio" id="ans" name="ans" value="1" />
<input type="radio" id="ans" name="ans" value="0" />
how will i get the value of ans
Id's must be unique, you should have the radio buttons with the same name, and get its value iterating through them:
<input type="radio" name="ans" value="1" />
<input type="radio" name="ans" value="0" />
var elements = document.getElementsByName('ans'), //or document.forms['name'].ans
i, el;
for (i = 0; i < elements.length;i++) {
el = elements[i];
if (el.checked) {
alert(el.value);
break;
}
}
getElementsByName('ans'), or document.forms['name'].ans returns an array object, containing the elements with the name ans.
I do not recommend having the same id for all 3 elements. You do have to have the same name for each button in order for it to be part of the group. If you have the form its in, you can do this
var myForm = document.getElementById('myForm');
var radioVal = myForm.ans.value;
That will give you your value.

Categories

Resources