select checkbox by name and check if it checked javascript - javascript

I am trying to test if checkbox is checked.
I have more inputs and they have different names.
I managed to select the input but I can't seem to check if it wa selected. If I add to the condition '= true' it is checked once I load the page. If I leave it just .checked it doesn't do anything
Have I selected the input right? Please note I want to select it by name rather than id or class
Why is it that once the page loads my condition for if statement doesn't work?
<input type="checkbox" name="name1">
<input type="checkbox" name="name2">
<input type="checkbox" name="name3">
<input type="checkbox" name="name4">
const firstInput = document.getElementsByName('name1');
if (firstInput[0].checked) {
console.log('checked');
}

You are selecting element with name "1" but don`t have element with such name.
If you want to select all inputs which name attribute starts with "name":
const firstInput = document.querySelectorAll('[name^=name]')

You need to add attribute to that input. Attach an onclick listener and invoke
getAttribute
setAttribute
to manipulate 'checked' attribute;
<input type="checkbox" onclick="myFunction()" name="name1">
<input type="checkbox" onclick="myFunction()" name="name2">
<input type="checkbox" onclick="myFunction()" name="name3">
<input type="checkbox" onclick="myFunction()" name="name4">
function myFunction() {
var $element = document.getElementsByName('name1')[0];
var checked = $element.getAttribute('checked') === 'true';
$element.setAttribute('checked', !checked);
console.log($element.getAttribute('checked'));
}

Related

Associate a checkbox with an input field and make it mandatory only if input value exists

I am trying to make a manual verification system and want the user to check each checkbox associated with individual inputs if a value exists before submission else the form would throw an error.
I have implemented this, but it does not seem to work. Also, I was wondering if there was a better way of achieving the same wherein we avoid passing the parameters to the function.
Similar to how we can associate a submit button for a form using form by supplying the id.
<form>
<input type="text" name="inputFieldOne">
<input type="checkbox" onblur="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo">
<input type="checkbox" onblur="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
<script>
function makeSureItIsSelected(field, checkbox){
let fieldBox = document.getElementsByName(field)[0];
if(fieldBox.value != ''){
checkBox = document.getElementsByName(checkbox)[0];
checkBox.required = true;
}
}
</script>
If you want to set the checkbox to be required when the field has a value, you should hook an event on the field, not the checkbox. input would make a good event for this:
function makeSureItIsSelected(field, checkbox){
let fieldBox = document.getElementsByName(field)[0];
let checkBox = document.getElementsByName(checkbox)[0];
// Require the checkbox when the field has a value
checkBox.required = fieldBox.value != '';
}
<form>
<input type="text" name="inputFieldOne" oninput="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')">
<input type="checkbox" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')">
<input type="checkbox" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
Note that there's no need for those calls to getElementsByName: Just pass this into the function, and use nextElementSibling to access the checkbox:
function makeSureItIsSelected(field){
// Require the checkbox when the field has a value
field.nextElementSibling.required = field.value != '';
}
<form>
<input type="text" name="inputFieldOne" oninput="makeSureItIsSelected(this)">
<input type="checkbox" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected(this)">
<input type="checkbox" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
That said, it seems odd to have the checkboxes at all. The presence of the field in the form data should be sufficient. But if the checkbox's value has to be in the form data, simply add it on submit without having a checkbox at all.

get radio value using jquery using .prop

I want a form where the user has 3 different radio buttons and once one is clicked a different message will display depending on which radio button they pick.
Here is some of my code:
if ($('#Jordanstown').prop('checked'))
{
alert("Yeah, we are on the same campus")
}
if ($('#Belfast').prop('checked')) {
alert("Ah, we are not on the same site")
}
<form name ="mycampous">
<input type ="radio" name ="Jordanstown">Jordanstwon</input>
<input type ="radio" name ="Belfast">Belfast</input>
<input type = "button" value="select" onclick= "campous();"> </input>
</form>
I'll change your HTML little bit to add a class to all radio buttons so that I don't have to use the input[type='radio'] selector which is slow.
Also radio buttons should have same name, if you want only one of them to be selected at any given time, so you need to mention some value to differentiate between two radio buttons like below
<form name ="mycampous">
<input class="radio" type ="radio" name="city" value ="Jordanstown">Jordanstwon</input>
<input class="radio" type ="radio" name="city" value ="Belfast">Belfast</input>
<input type = "button" value="select" onclick= "campous();"> </input>
</form>
And then in your script, look for the change event on these radio buttons
$(document).ready(function(){
$('.radio').on('change', function(e){
var radioValue = $(this).val();
if(radioValue === 'Jordanstown'){
alert("Yeah, we are on the same campus");
} else if(radioValue === 'Belfast'){
alert("Ah, we are not on the same site");
}
});
});
Here's a bin to play with :)
Try something like this:
<script>
function campous(){
var value = $("[name='mycampous']").find("input[type='radio']:checked").val();
alert(value);
}
</script>
<form name="mycampous">
<input name="campus" type="radio" value="Jordanstown">Jordanstwon</input>
<input name="campus" type="radio" value="Belfast">Belfast</input>
<input type="button" value="select" onclick="campous();"> </input>
</form>
http://jsfiddle.net/p7Lj1bL6/
Try:
<input type ="radio" name ="Jordanstown" id="Jordanstown">Jordanstwon</input>
<input type ="radio" name ="Belfast" id="Belfast">Belfast</input>
<input type = "button" value="select" onclick= "campous();"> </input>
</form>
I added the id attributes since $('#Belfast') is selector for the ID not NAME.
I take it that you have the javascript sample wrapped in click event, something like this:
$('form').on('click', ':radio', function(){
if ($('#Jordanstown').prop('checked'))
{
alert("Yeah, we are on the same campus");
}
if ($('#Belfast').prop('checked')) {
alert("Ah, we are not on the same site");
}
});
Preferably, you should also have given the form an id to narrow down the DOM search.
EDIT
I just re-read your question. You're trying to alert the clicked radio. It should be:
$('form#ID_OF_FORM').on('click', ':radio', function(){
if( $(this).is('#Jordanstown') ){
alert("Yeah, we are on the same campus");
}else{
alert("Ah, we are not on the same site");
}
});
Provided your form's ID is ID_OF_FORM.

What value passes from a form with checkbox to the java script

I take a form and wants value of checkbox.
such as:
<form method="post" onSubmit="return nameempty()">
<input name="checkn1" id="check1" type="checkbox" />
<input name="checkn2" id="check2" type="checkbox" />
<input type="submit" value="submit">
</form>
Now I want to know the values of checkbox when it is selected, and also when not selected.
Now I write javascript, and get that each checkbox has value "on" whether it is selected or not.
<script>
function nameempty()
{
alert(document.getElementById('check1').value);
alert(document.getElementById('check2').value);
}
</script>
How could I get 'on' when it is selected and anything else when not selected.
use checked instead of value which will return true if the checkbox is checked or it will return false
<script>
function nameempty()
{
alert(document.getElementById('check1').checked);
alert(document.getElementById('check2').checked);
}
</script>
One way to get the value of a 'checked' check box which includes the check if 'checked'
var check1value = document.querySelector('#check1:checked').value;
In the html you are missing a value attribute (if checked)
<input name="checkn1" id="check1" value="value-here" type="checkbox" />

how to get the value of the hidden fields in here after the radio button is clicked

Am trying to get the value of the hidden input fields on every click of a radio button. I have just posted a single div. I have a multiple div with same structure. I have successfully obtained the value of radio button but I want to get the value of hidden input now.
<div class="QA">
<h1> First Question</h1>
<input type="radio" id="check" name="q" value="A">Options 1</input>
<input type="radio" id="check" name="q" value="B">Options 2</input>
<input type="radio" id="check" name="q" value="C">Options 3</input>
<input type="radio" id="check" name="q" value="D">Options 4</input>
<input type="hidden" id="result" value="B" />
<br/>
<div id="result"></div>
</div>
<script>
$(document).ready(function() {
$("input:radio").change(function() {
checkResult(this);
});
});
function checkResult(el)
{
$this=$(el).parent("div.QA");
$this.slideUp();
}
</script>
Maybe you could try removing the hidden input entirely and indicate the correct answer using a data-* attribute. Something like:
<div class="QA" data-answer="B">
Then in your checkResult function you could retrieve this value using
function checkResult(el)
{
$this=$(el).parent("div.QA");
var answer = $this.data("answer");
$this.slideUp();
}
function checkResult(el)
{
$this = $(el).parents("div.QA");
$this.slideUp();
var x = $this.find('#result').val(); //find value of hidden field in parent div
}
Change your markup
multiple id's should not be used. Use class instead.
<input type="radio" id="check" name="q" value="A">Options 1</input>
to
<input type="radio" class="check" name="q" value="A">Options 1</input>
var $hidden=$(el).siblings("input[type='hidden']");
BTW you have lot of elements with same ID, not good
You can get the value of the hidden element by it's id.
var hiddenValue = $("#result").val();
You can use this in hidden function
function checkResult(el)
{
var hiddenValue = $("#result").val();
alert(hiddenValue);
}

Need amount of checkboxes checked to influence number in link

I have these three checkboxes and a button that connects to another page. When that button is clicked, I want it to go to a page that is linked to the checkbox(es) that are checked.
<div data-role="content" data-theme="a">
<h2>Checkboxes</h2>
<div data-role="fieldcontain">
<input type = "checkbox" name = "nameOne" id = "checkBoxOne" checked = "checked" />
<label for = "checkBoxOne">Checkbox One</label>
<input type = "checkbox" name = "nameOne" id = "checkBoxTwo" />
<label for = "checkBoxTwo">Checkbox Two</label>
<input type = "checkbox" name = "nameOne" id = "checkBoxThree" />
<label for = "checkBoxThree">Checkbox Three</label>
<p>Continue</p>
</div>
</div>
Now when no checkboxes are checked, I want the href to link to '#linkToPage1', when the first checkbox is checked, I want it to link to '#linkToPage2', when the second is checked '#linkToPage3', when the third is checked '#linkToPage4', when first and second are checked '#linkToPage5', and so on.
So the '#linkToPageX' should change according to the checkbox(es) that are checked.
<input type="checkbox" checked="checked"/>
<input type="checkbox" checked="checked"/>
<input type="checkbox" checked="checked"/>
<input type="checkbox" checked="checked"/>
<input type="checkbox"/><br/>
<script>
document.write("The no of checked checkbox :"+$("input:checkbox[checked='checked']").length);
</script>
You can use the jquery selectors for find the no of checkbox checked
Recent browsers have querySelectorAll :
document.write("HTML5 : number of checked checkbox :" +
document.querySelectorAll ("input[type='checkbox'][checked='checked']").length);
Try it on your browser on http://jsfiddle.net/LwtvK/

Categories