I have a radio button on my html page and I'd like to test the value of the current selected option
<div>
<input type="radio" name="radio1" value="enabled" checked/>
<label for="radio1">Yes</label>
</div>
<div>
<input type="radio" name="radio1" value="disabled" />
<label for="radio1">No</label>
</div>
<br />
I'm using this code on the page object I use to test
var radio = $("input[type='radio'][name='radio1']:checked").val();
Unfortunately I get
val() is undefined
How can I return "enabled" or "disabled" based on the current status of the radio button?
val() is a jQuery function which you do not inherently have access to unless you setup Protractor that way. Use getAttribute('value') instead, which returns a promise - see the getAttribute() reference
So if you are using it in an assertion, you can let expect resolve the promise itself:
var radio = $("input[type='radio']:checked")
expect(radio.getAttribute('value')).toEqual('enabled');
Or if you want to access the value and use it elsewhere, resolve the promise yourself:
radio.getAttribute('value').then(function (val) {
if(val === 'enabled') {
// code
}
});
Instead of 'enabled' the value = 1
// using TS
static myElement = element
.all(by.css('input[type="radio"]:checked'))
.get(0);
expect(this.myElement.getAttribute('value')).toEqual(
'1'
);
Related
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
ive got the (working) following code
$('#selBookable').change(function () {...
and
<div class="radio radio-search">
<label><input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" >Neueste</label>
which executes when #selBookable gets another value.
Now i want to execute this function when a Radio button somewhere else is clicked.
i tried :
$('#selBookable, #radio-new-pop').change(function () {...
but that does not work.
now i thought about giving this ".change(function NAMEHERE"
a name and execute that function but doesnt work either.
any help is appreciated.
edit: i tried using the onchange event but then again i have no function name to call.
You could define the function independently of its use, giving it a name. Then you could attach it to as many targets you wish, making a call as the one that works (using the name instead of the definition), each with a different target.
(The reason your second attempt didn't work is that the second argument to $ is not another target to attach the function to, but a constraint on where to find the first target.)
You have two buttons radio with the same name :
<div class="radio radio-search">
<label>
<input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" />
Neueste
</label>
<label>
<input id="radio-new-pop2" type="radio" name="radio_newest_popular" value="new" />
Other
</label>
</div>
Add a javascript function to handle this change :
var onRadioButtonChange = void 0;
{
onRadioButtonChange = function (e) {
theFunctionYouWantToExecute(); // pass this or e.target if needed
return false;
}
}
Attach it to your elements :
Array.prototype.forEach.call(
document.querySelectorAll('input[type="radio"]'),
function (element) {
element.addEventListener('change', onRadioButtonChange, false);
}
);
Perhaps try putting the jquery listener inside of a $(document).ready().
OR
You could add a click handler on the radio, like this:
<div class="radio radio-search">
<label>
<input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" onclick="handleClick(this)">
Neueste</label>
and in the JS:
handleClick(myRadio) {
// click function logic
}
Adapted from this answer.
im working on a small app but i cant resolve this
im trying to use jQuery to append checked radio to the form , i did try alot of solution but i did fail
i wrote the code here , hope someone can help me to resolve this issue
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios" value="interior">
Interior
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios" value="exterior">
Exterior
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios" value="interio+exterior">
Interior si exterior
</label>
</div>
Here data was fetchted using json and i have the right result
<script>
$.each(data, function (k, v) {
typdespal = v.typdespal;
// the problem is that always i cant get the radio checked in the right position from the database
// $('#optionsRadios').val(typdespal);
$("input:radio[name='optionsRadios']").val(typdespal).prop( "checked", true );;
</script>
You can use filter() to find the correct radio button with value then set its property to checked.
$("input:radio[name='optionsRadios']").filter(function(){
return $(this).val() === typdespal
}).prop( "checked", true);
First, you need to wrap this all in a Document.Ready call. Then you need to only apply the checked function to the checkbox which contains the appropriate value. At the minute you are setting the value of all optionsRadios. You can do this with the prop function overload:
$(function() { // DOM ready
$("input:radio[name='optionsRadios']").prop("checked", function() {
// Only set the checked value when this checkbox value === the corresponding data value
var val = $(this).val();
return val === data[val].typdespal;
});
});
Note: I think I'm reading your data object right, hard to tell without seeing it :)
Firstly, several radio buttons may have same name, but not ID. So make them unique. Secondly, try to change your selector to:
$("input:radio[value='"+typdespal+"']").prop( "checked", true );
What I am trying to do is to populate my input fields based on JSON object. Below are the fields with their default values:
<input type="hidden" name="id"/>
<input id="enabled1" name="enabled" type="checkbox" value="true"> // not sure why value="true" here, by default it should be false
The JSON object has the following format:
[{enabled:false, id:184}]
Based on the JSON object, I will iterate its properties and assign the value to the field accordingly. The iterate function is as follows:
for ( var propertyName in aData) {
if (aData.hasOwnProperty(propertyName)){
// check if field exist
var elem = $("input[name="+propertyName+"]");
var exist = elem.size() == 1;
// if exist, update field with selected info
if (exist){
elem.val(aData[propertyName]);
}
}
}
After the iterate function runs the fields are shown like below:
<input type="hidden" name="id" value="184">
<input id="enabled1" name="enabled" type="checkbox" value="false">
Now if I tick the checkBox and submit the information to server, I want the value to be true but somehow the value is still false. What did I miss out here ?
But that's very much expected. Since, selecting a checkbox does not have any effect on the value of the html element it changes the checked status from unchecked to checked. When you try to get the value on the server side it would return you with the overridden value.
Check it out here
I'm not sure, but I think input tag should have close tag (slash /) in itself:
<input type="hidden" name="id" value="184"/>
<input id="enabled1" name="enabled" type="checkbox" value="false"/>
Please check. -Han-
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");" />