Set checkbox to be checked if input value = - javascript

I have an input and a checkbox. I have managed to change the value in the input on clicking the checkbox, and un clicking etc which works fine.
I'm looking to auto set the checkbox to be checked on page load only if the input value = yes, as this input value is being loaded dynamically via php and may not be yes.
HTML
<input type="text" value = "yes" id ="inputId">
<input type="checkbox" id = "yourCheckboxId">
JQUERY
$('#yourCheckboxId').click(function() {
if ($('#yourCheckboxId').is(':checked')){
$('#inputId').val('yes');
}
if (!$('#yourCheckboxId').is(':checked')){
$('#inputId').val('no');
}
});
You'll notice that even though the value in the input is set to yes, on page load, the checkbox isn't checked. This is what I have so far, see jsfiddle here: http://jsfiddle.net/0z9agrw8/1/
Thanks

var input = $('#inputId').val()
if(input === "yes"){
$("#yourCheckboxId").prop('checked', true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value = "yes" id ="inputId">
<input type="checkbox" id = "yourCheckboxId">

Do this on page load:
if($('#inputId').val() == 'yes') {
$('#yourCheckboxId').prop('checked', true);
}

If you always want it to be checked on page load, you can simply add the "checked" attribute
eg
<input type="checkbox" id = "yourCheckboxId" checked>
If it's more complicated than that, the other answers will work nicely

Related

How to set the name attribute of a toggled input field on change event

I am trying to change the attribute name="" value of an input field that is toggled once a check box is set and a toggled input is shown and filled out.
User checks a check box, once the check box is checked an input field shows where the title once was. I got this part covered.
Once the input field shows, I want to change the name attribute in that input field with the value the user inputs all before submission of form.
Here is the code I have tried...
document.getElementById('custom-check-box').addEventListener('click', function() {
if (this.checked) {
document.getElementById('custom-span').innerHTML = '<input type="text" id="customInputName" name="customInputName" placeholder="Name the custom attribute">';
} else {
document.getElementById('custom-span').innerHTML = 'Custom: ';
}
});
// this bit of code is not working as intended. I want to get the input
// value after the user changes or focus out of the input and then have that
// value input into the name attribute for the same input.
document.getElementById('customInputName').addEventListener('change', function() {
if (this.onChange) {
let value = document.getElementById('customInputName').value;
this.setAttribute("name", value);
}
});
<div title="'.$title.'" class="input-info">
<span id="custom-span">Custom:</span> Yes: <input id="custom-check-box" type="checkbox" class="input-check" name="custom" value="yes">
</div>
Error: Cannot read property 'addEventListener' of null
I think it is because the input is not set yet in the DOM. Should I set the input in HTML, hide it and then change the name attribute and then show it?
Any help would be greatly appreciated as I am a bit of a beginner with JavaScript.
Thank you in advance!
SEE ACCEPTED ANSWER FOR UPDATE ON WORKING CODE. -> Second snippit was added an edit to #CertainPerformance code that works better for my use.
I'd create the <input> outside of any of the handlers, and give it the listener which assigns its value to its name. When the checkbox is checked, append the input to the container, otherwise clear the container:
const input = document.createElement('input');
input.name = 'customInputName';
input.placeholder = 'Name the custom attribute';
const customSpan = document.getElementById('custom-span');
document.getElementById('custom-check-box').addEventListener('click', function() {
if (this.checked) {
customSpan.textContent = '';
customSpan.appendChild(input);
} else {
customSpan.textContent = 'Custom: ';
}
});
input.addEventListener('change', function() {
input.name = input.value;
});
<div title="'.$title.'" class="input-info">
<span id="custom-span">Custom:</span> Yes: <input id="custom-check-box" type="checkbox" class="input-check" name="custom" value="yes">
</div>

How to display a textbox if "others" option from checkbox group is checked

I want to display a text box using JavaScript when the "Other" option is checked from a group of checkboxes. I'm using razor pages with asp.net core 2.2
I'm using the following script but it is not working.
function onSelectChange() {
var sel = document.getElementById('QuestionOptionId');
var strUser = sel.options[sel.selectedIndex].text;
if (strUser.startsWith('Other'))
document.getElementById('textBox').disabled = false;
else
document.getElementById('textBox').disabled = true;
}
</script>
Fruits.cshtml ( razor page view file)
#foreach (var option in Model.QuestionOptions)
{
<input type="checkbox" asp-for="QuestionOptionId" id ="QuestionOptionId" value ="#option.Value" onclick="onSelectChange()" /> #option.Text<br />
}
QuestionOptions is a selectList:
Value=1 Text= Apple,
Value=2 Text= Kiwi,
Value=3 Text =Other
whenever the user checks the checkbox for "Other", it should display a textbox.
What am I doing wrong here? I have read so many other answers but not able to figure out this one.
Update-1
I don't know why the post is not showing the textbox control...
I'm pasting it here again, it is outside the foreach loop. I have removed the angle brackets as I think it is mixing with formatting.
input type="text" id="textBox" name="response" disabled="disabled"
Full disclosure: I have never used Razor pages or asp.net
I'm having a hard time following how your javascript is detecting whether the other option is checked. It seems like your Fruits.cshtml is going to generate three separate inputs with the same "QuestionOptionId" id.
Also, your Fruits.cshtml snipped doesn't include the code for the textbox you'd like to enable, though I'm assuming you have a textbox with id "textBox" in the compiled HTML that you'd like to enable.
I would change your script out for this:
function onSelectChange(element) {
if (element === element.parentNode.querySelector(".other")) {
console.dir(element);
if (element.checked) {
document.getElementById("textBox").disabled = false;
} else {
document.getElementById("textBox").disabled = true;
}
}
}
You'll need to add the "other" class to your applicable "Other" input checkbox. You'll also need to change your Fruits.cshtml snippet so that the "onclick" function also passes the applicable element into the script.
#foreach (var option in Model.QuestionOptions)
{
<input type="checkbox" asp-for="QuestionOptionId" id ="QuestionOptionId" value ="#option.Value" onclick="onSelectChange(this)" /> #option.Text<br />
}
Here's a working example of the compiled code: https://codepen.io/bourn404/pen/yWVLdx
Try the following modification in the view and the javascript:
Add the label outside the input
#foreach (var option in Model.QuestionOptions)
{
<Lable>
<input type="checkbox" asp-for="QuestionOptionId" id="QuestionOptionId" value="#option.Value" /> #option.Text
</Lable>
<br />
}
<div>
<input type="text" id="textbox" disabled="disabled" />
</div>
Use $(this).parent().text().trim() to get the text
$('input:checkbox').on('click', function () {
if ($(this).parent().text().trim() === "Other") {
$('#textbox').removeAttr("disabled");
}
});
Update
If you want to hide the text box and hide the textbox when you uncheck the "other option , firstly you could change the disabled attribute to hidden ,and then determine if the text box contains hidden attribute in js like below :
<input type="text" id="textbox" hidden />
if ($(this).parent().text().trim() === "Other")
{
if ($('#textbox').is(':hidden')) {
$('#textbox').removeAttr("hidden");
}
else {
$('#textbox').attr("hidden", "hidden");
}
}

Cant validate radio checked properly as DOM returns values before validation is executed

Sorry for the tittle might be quite confusing.
I have a radio check box, if clicked once it gets checked if clicked again it gets unchecked.
<label class='container'><p1 style='font-size: 14px'>Able to fit several products</p1>
<input type='radio' name='Delivery' id='Delivery' onclick='radio_check();'>
<span class=checkmark></span>
</label>
var radio = document.getElementById("Delivery")
if(radio.checked){
radio.checked = false;
}else{
radio.checked = true;
}
The problem with this code is that it will always return radio.checked = false. If the radio is unchecked and user checked it, this function would still return false because the value send to this is that the radio was checked, how can i fix this issue?
https://jsfiddle.net/o2ayejz9/
use checkbox instead of radio
https://jsfiddle.net/o2ayejz9/1/
<input type='checkbox' name='Delivery' id='Delivery' onclick='radio_check();'>
updated your fiddle

make a input field required if radio is checked

Can I somehow insert the required attribute into an input field only if a certain radio is checked?
I have an input field named "ladder-meters" that is not required to be filled per default. But if the user checks a radio button that is named "ladder" the "ladder-meters" field are required to be filled.
My input looks like this:
<input type="text" name="ladder-meters" id="ladder-meters">
and should like this at the onchange event on the radio
<input type="text" name="ladder-meters" id="ladder-meters" required>
document.getElementById("ladder").addEventListener('change', function(){
document.getElementById("ladder-meters").required = this.checked ;
})
Whenever the checkbox is clicked, the required attribute will be changed to match the checked attribute of the checkbox. To reverse this relationship, replace this.checked with !this.checked
This may need some adjustment to suit your specific project.
This will work with this checkbox:
<input type='checkbox' id='ladder' name='ladder' />
Tried F. Orvalho, didn't work for me, I had to use
$('#ladder').change(function () {
if(this.checked) {
$('#ladder-meters').prop('required', true);
} else {
$('#ladder-meters').prop('required', false);
}
});
It could be usefull. Thx to F. Orvalho for the structure
Easy to achieve with jQuery:
$('#ladder').change(function () {
if($(this).is(':checked') {
$('#ladder-meters').attr('required');
} else {
$('#ladder-meters').removeAttr('required');
}
});

how to call a javascript function on radio button's 'checked' property?

I have N number of radio button groups in the page with auto generated names.
I want to call a javascript function as the value of the checked property. THIS LINE EXCLUDED AFTER EDIT ( Depending on the return value, the radio button needs to be checked or unchecked.)
<input type="radio" name="auto_generated_name" value="some_value" checked="test_check(args);" />
and the javascript function is
function test_check(params) {
if(conditions){
return true;
}
else
return false;
}
But that does not work. Whatever value I assign to 'checked' property, be it any javascript function or any string etc, the radio button becomes checked.
How can I achieve my goal?
EDIT:
<input type="radio" name="auto_generated_name" value="somevalue" onclick="test_check(args)"/>
4 radio buttons make a group. such N radio groups have html class names in this way : button_group_1, button_group_2, button_group_3, button_group_4 etc.
The 'args' need to be these class (i.e. radio button group) names and the corresponding values (from value="1", value="2", value="3" and value="4" ).
Cookies with the class names and values will be created inside the javascript function.
On page refresh, cookies matching with the class names will be checked and depending on the existence of the corresponding cookies, the radio button will be checked or unchecked.
How to achieve the goals/
Assuming you are using jQuery, use the change event: http://api.jquery.com/change/
The checked attribute is simply a boolean value to indicate whether the radio button should be checked, it cannot contain script, or a reference to a scripting function. Any value in the attribute will cause the radio button to be checked.
Without knowing what mechanism you are using to check each radio button - I can see an args variable but don't know what type this is - it's going to be tricky to write some code for you.
If you can make args into an array of values, then something along the lines of the following should work for you:
var args = new Array(true,false,true)
$.each(args, function(index, value) {
$("INPUT[type=radio]").eq(index).attr("checked", value)
});
Here's a fiddle to show what I mean more clearly
check this output, valid args is 'aa'.
http://jsfiddle.net/X7rcC/1
html:
<input type="radio" name="auto_generated_name" value="some_value1" checked="bb" />
js:
$(function() {
var radios = $("input[type='radio']");
$.each(radios, function(index, value){
var args = value.attributes[1].nodeValue;
test_check(args, value);
})
});
function test_check(params, value){
if(params == "aa"){
$(value).attr("checked",true);
}else
$(value).attr("checked",false);
}
try this:
Here I user a custom attribute to input named groupname. In OP's case groupname="<?php echo $radio_button_group_name; ?>". Then checking the value of this attribute OP can assign checked attribute value.
<input type="radio" name="r1" groupname="gr1"/>
<input type="radio" name="r2" groupname="gr2"/>
$('input:radio').each(function() {
if ($(this).attr('groupname') == 'gr1') {
$(this).attr('checked', true);
} else {
$(this).attr('checked', false);
}
});
Your question really boils down to:
How can I set the value of a checkbox when the page first loads? (Using a parameter stored with the checkbox)
The key insights are:
you can't store a function inside a parameter and expect it to automatically evaluate on load
you can store the data about an object inside data- properties
you can set the value of objects on page load in jQuery using the $(document).ready() event
.
<script type="text/javascript">
$(document).ready( function() { // this code runs when the page is first loaded
var radios = $("input[type='radio']"); // find all of your radio buttons
$.each(radios, function(){
var radio = $(this);
var param = radio.attr('data-param'); // retrieve the param from the object
radio.attr('checked', test_check(param) ); // set the value of the radio button
})
});
function test_check(params) {
if(conditions){
return 'checked';
}
else
return '';
}
</script>
You cannot use a checked attribute this way, because anything as the value will be the same as checked=true Even just checked checks a radio button. What you should do is use a custom attribute which will create the checked attribute:
<input type="radio" name="auto_generated_name" value="some_value" needs_check="param">
<script>
// Do test_check on param for each input
$('input:radio').each(function()
{
var radio = $(this);
var param = radio.attr('needs_check');
var condition = test_check(param);
radio.attr('checked', condition);
});
function test_check(param)
{
return true or false based on param
}
</script>
I was facing same problem and my conclusion is that don't use " " to contain a function.
Correct:
<input type="radio" name="im" id="b1" onclick=alert("hello"); />
Incorrect:
<input type="radio" name="im" id="b1" onclick="alert("hello");" />

Categories