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");" />
Related
I've had a problem where I wrote a checked() function for the onchange of a checkbox:
<input
type="checkbox"
id = "checked"
onchange="checked()"
/>
Here's my javascript:
const check = document.getElementById("checkbox")
const yes = document.getElementsByClassName("yes")
function checked() {
if (check.checked) {
yes.innerHTML = "Yes"
} else {
yes.innerHTML = "No"
}
}
Basically I want the span with the class of yes to change output depending on if the checkbox is checked or not (Says Yes or No)
However, when I inspect, it says "TypeError: checked is not a function
at HTMLInputElement.onchange" even though my javascript is perfectly linked to my HTML (I checked this with an alert).
How can I solve this?
You're getting checkbox by id checkbox, but in your input field, you put id="checked" which is incorrect, so you need to correct your id from checked to checkbox.
<input
type="checkbox"
id = "checkbox"
onchange="checked()"
/>
You also need to change your function name from checked to another name (like checkData which is not similar with native values/functions) and then wrap your document.getElementById into your function
You should not use getElementsByClassName too, because it returns a list of elements and innerHTML does not work for those, so you need to select a particular element with getElementById
function checkData() {
const check = document.getElementById("checkbox")
const yes = document.getElementById("yes") //need to use `getElementById` instead of `getElementsByClassName`
//if `yes` element is not there, we don't need to set `innerHTML`
if(!yes) {
return
}
if (check.checked) {
yes.innerHTML = "Yes"
} else {
yes.innerHTML = "No"
}
}
Remember to implement your yes element like this
<p id="yes"></p> //tag name is your choice
Technically, checked is the name of the value attribute on that input and it's not a function, so you cannot use it as a function name.
By the way, thank #Teemu for the suggestion!
const check = document.getElementById("checkbox")
There is no such ID in your code named "checkbox". I think you want:
const check = document.getElementById("checked")
Try giving your IDs, function names and input-types unique names so you won't get them mixed up with each other.
I am trying to assign values I get from an endpoint to a checkbox
Here is the object
{sendOtpEmail: true}
I had to do some searching inside the endpoint response to differentiate whether an email value comes back or a cell phone value comes back
Here is my code
TS
otpCellValue: any;
otpEmailValue: any;
getOTPChannel() {
this._loader.start();
this._subscriptions.push(this._corpService.getOTPChannel().subscribe((resp) => {
//get endpoint object
console.log(resp);
//get endpoint object parameter name
let keyNames = Object.keys(resp);
console.log(keyNames[0]);
//check for email keyword
if(keyNames[0].includes('Email')) {
console.log(resp.sendOtpEmail);
//get value
if(resp.sendOtpEmail == true) {
//email value is true so the otpEmailValue checkbox should be checked however it is not
this.otpEmailValue = 1;
this.otpCellValue = 0;
} else {
this.otpEmailValue = 0;
this.otpCellValue = 0;
}
}
this._loader.stop();
}, (error) => {
this._loader.stop();
this._errorService.openErrorPopup('Failed to get OPT channel.');
}));
}
HTML
<input type="radio" name="1" id="1" class="with-gap" [(ngModel)]="otpCellValue" [(value)]="otpCellValue">
<input type="radio" name="2" id="2" class="with-gap" [(ngModel)]="otpEmailValue" [(value)]="otpEmailValue">
I added comments to say what I am doing in the code above
So now I am stuck with why the email checkbox is not checked. Any ideas?
Those are not checkboxes but radio buttons. Assuming that you do want the radio buttons (which in your case it looks like it, because it would be one or the other), there are a few things that needs to be done.
Rather than having 2 properties to indicate which option is selected, you could have 1 property for that purpose.
So
this.otpEmailValue = 1;
this.otpCellValue = 0;
Becomes
this.contact = 'email'; // This line is now equivalent to the ones above
In the template, the radio button inputs, need to have the same name for them to behave as 1 input instead of 2, because after all, we only want 1 option selected. The ngModel directive now points to the value we want to bind, in our case, contact. And lastly, the value should be static. When the value of the property bound with ngModel matches the value of one of the radio buttons, it will select it.
So, after all those changes we get the following.
<input type="radio"
name="contact-option"
id="1"
class="with-gap"
[(ngModel)]="contact"
value="cell"> Cell
<input type="radio"
name="contact-option"
id="2"
class="with-gap"
[(ngModel)]="contact"
value="email"> Email
Demo
I'm trying to create a simple HTML page that presents a user with several options via checkboxes. I need to generate a string, stored in a variable that I can use on the page when a button is clicked, which will vary based on which boxes are checked.
The string will be a URL ("http://example.com/index.htm&term=") and will need to have additional text appended to it for each checkbox that is checked.
For example, if only a single box, say box1, is checked the string "box1" should be appended to the URL variable to look like "http://example.com/index.htm&term=box1"
If, however more than one box is checked, say box2 and box3 are checked, then the string "box2%20OR%20box3" should be appended to the URL string.
I'm pretty sure this can be done with JavaScript but I have no experience with it and would appreciate some guidance/examples.
Instead of storing it in a variable, I would recommend calling a function that builds the link when the button is pressed. If you really wanted to put it in a variable though, you would set up an event listener for the change event for each checkbox, and call the function to update the variable each time one of the checkboxes is checked or unchecked.
function checkboxUrl(checkboxes) {
const
url = `http://example.com/index.html`,
checkedArray = [];
for (let checkbox of checkboxes) {
if (checkbox.checked) checkedArray.push(checkbox);
};
const checkboxString = checkedArray.map(checkbox => checkbox.value).join(`%20OR%20`);
return url + (checkboxString ? `?term=` + checkboxString : ``);
}
let checkboxes = document.querySelectorAll(`input[type='checkbox']`);
label {
display: block;
}
<label><input type='checkbox' value='box1'>box1</label>
<label><input type='checkbox' value='box2'>box2</label>
<label><input type='checkbox' value='box3'>box3</label>
<button onclick='console.log(checkboxUrl(checkboxes))'>Get URL</button>
If you use Jquery you can do something like this:
<input type="checkbox" id="box1">
<input type="checkbox" id="box2">
<button type="button" id="myButton">Submit</button>
<script>
$(document).ready(function(){
$('#myButton').click(function(){
var url = 'www.myurl.com/index.html&term=';
var checkboxList = [];
var params = '';
$(':checkbox:checked').each(function(){
checkboxList.push($(this).attr('id'));
});
params = checkboxList.join('%'); //will output "box1%box2"
url += params //www.myurl.com/index.html&term=box1%box2
window.location.href = url;
});
});
</script>
I am trying to select some radio button on a webpage using Javascript inside Tampermonkey. For this particular button, there is no element ID, so I'm not really sure how to select them.
There's really no other identifying elements for these buttons that I can see.
Note: There's several radio buttons on this page, and the only unique identifier between them is the "value." There are 12 other buttons, but I want these 3 selected by default after the page loads.
<input name="Offense" type="radio" value="Indifferent">
<input name="Likelihood" type="radio" value="Indifferent">
<input name="Humor" type="radio" value="Indifferent">
So, I tried to catch them all at once with this:
document.getElementByValue("Indifferent").checked = true;
but it's not doing anything, I'm sure I'm missing something.
Thank you!
Using querySelector/querySelectorAll from Selectors API returns a NodeList of matching DOM Nodes. Since it is not an Array, a for-loop is used:
var inputs = document.querySelectorAll('input[value="Indifferent"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
}
The same in jQuery:
$('input[value="Indifferent"]').attr('checked', true);
// list will contain all the radio buttons
var list = $('input[value="Indifferent"]')
$.each(list, function(index, value) {
alert( index + ": " + value );
});
All the data you need will be in the value object
https://jsfiddle.net/o46rhpwL/
And if you are looking for the checked value in the list
https://jsfiddle.net/z73ah82b/
I have a gender field in my form.
I have given it the same name, i.e. 'gender', and I have given it the same id, i.e. 'gender'.
Now I want to show what I have selected out of the two options. But with same id, it is not working. I have applied the onclick event to a textbox and I want it so whenever I click on that textbox, I show a javascript alert showing what I have selected, either male or female.
Please help!
gender:<input type="radio" name="gender" id="gender" value="female"/>female
:<input type="radio" name="gender" id="gender" value="male" />male
<input type="text" name="textbox" onclick="check()" />
<script type="text/javascript">
function check()
{
var a=document.getElementById("gender").value;
alert(a);
}
</script>
function addUser() {
//how to check what is the selected radio input
alert(getCheckedRadioId('u_type'));
}
function getCheckedRadioId(name) {
var elements = document.getElementsByName(name);
for (var i=0, len=elements.length; i<len; ++i)
if (elements[i].checked) return elements[i].value;
}
</script>
now this code alerts that what i have choosen but the problem is that i want the alert's value in a variable so that i could send this value to database...so how should i take the alerted value in a variable.....
You might wanna have a look at this:
javascript selected radio
Basically if you had a function that gets the checked radio value by name the problem would be solved. Adopted from the link above:
var selected = '';
var elements = document.getElementsByName('gender');
for (var i = 0, i < elements.length; i++)
{
if (elements[i].checked)
selected = elements[i].value;
}
alert(selected);
Also you might consider using jQuery. It would help a lot in cases like this one.
Your problem is that each element must have a unique Id, and you are giving two elements the same Id. I am not sure which one getElementById() would return. I assume the first.
However, you are quite ok giving multiple elements the same name. Then you could use getElementsByName() to retrieve an array containing the two elements, and you could return whether the element's Checked property is set.