Radio button with jQuery and AJAX - javascript

I've got the following error when i'm sending the form, to be exact with radio button input.
Here is the HTML Code:
<input name="radio" type="radio" class="raido-btn" id="coral1" value="coral1" />
<label for="coral1">CORAL I</label>
<input name="radio" type="radio" class="raido-btn" id="coral2" value="coral2" />
<label for="coral2">CORAL II</label>
<input name="radio" type="radio" class="raido-btn" id="coral3" value="coral3" />
<label for="coral3">CORAL III</label>
Here is the Javascript code:
if($('#coral1').prop('checked')){
apartamentos = 'Coral 1';
}
else if($('#coral2').prop('checked')){
apartamentos = 'Coral 2';
}
else if($('#coral3').prop('checked')){
apartamentos = 'Coral 3';
}
I don't know how to set the variable "apartamentos" to the radio button which is checked.
It always set the variable apartamentos = 'Coral'
Thanks in advance

JQuery has a few ways to do this. One way I usually do it is by using .is(), for example, $('#coral2').is(':checked'). You could also use apartamentos = $('.raido-btn:checked').val()

What are you attaching that if statement to? I attached it to the clickevent in jsFiddle and and it seems to be working fine. I'm not sure if you want apartamentos to be set to the value of the radio button or the strings that you defined, but it's definitely being updated.
http://jsfiddle.net/FTT5e

Related

Get value of checked radio button in radio button in Angular JS which as ng-repeat

Here is the code on selection of any one of the radio button i need to get the value
<label ng-repeat="SurveyType in SurveyTypes">
<input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeName" ng-value="{{surveyData.SurveyTypeName}}" />
{{SurveyType.Name}}
</label>
You should assign value from your repeat-loop not from model value and no need to use {{}} for ng-value
so use ng-value="SurveyType.Name" instead of ng-value="{{surveyData.SurveyTypeName}}" so selected radio button value set to surveyData.SurveyTypeName.
If you want to select anyone by default you can assign value to surveyData.SurveyTypeName like $scope.surveyData={SurveyTypeName: 'second'} then that radio button shown as selected that has value second.
HTML:
<label ng-repeat="SurveyType in SurveyTypes">
<input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeName" ng-value="SurveyType.Name" />
{{SurveyType.Name}}
</label>
PLUNKER DEMO
Your HTML should be like this.
<input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeName" ng-value="{{surveyData.SurveyTypeName}}" ng-change="getval($index)"/>
Js
$scope.getval = function (index){
var servetypename =SurveyTypes[index];
var data =servetypename.SurveyTypeName
}
Don't know from surveyData.SurveyTypeName is coming from.
<li ng-repeat="SurveyType in SurveyTypes">
<input type="radio" name="SurveyTypeName" ng-model="$parent.rdoSelected" ng-value="SurveyType.SurveyTypeName" />
{{SurveyType.Name}}
</li>
PLUNKER

Hide div for Radio button selected value using jquery- Not working

I want to hide a div (AppliedCourse), when radi button value is Agent. I wrote below code but it is not working.
Any idea?
$('#HearAboutUs').click(function() {
$("#AppliedCourse").toggle($('input[name=HearAboutUs]:checked').val()='Agent');
});
<tr><td class="text"><input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other</td></tr>
Either your HTML is incomplete or your first selector is wrong. It is possible that your click handler is not being called because you have no element with id 'HeadAboutUs'. You might want to listen to clicks on the inputs themselves in that case.
Also, your logic is not quite right. Toggle hides the element if the parameter is false, so you want to negate it using !=. Try:
$('input[name=HearAboutUs]').click(function() {
var inputValue = $('input[name=HearAboutUs]:checked').val()
$("#AppliedCourse").toggle( inputValue!='Agent');
});
I have made a JSFiddle with a working solution: http://jsfiddle.net/c045fn2m/2/
Your code is looking for an element with id HearAboutUs, but you don't have this on your page.
You do have a bunch of inputs with name="HearAboutUs". If you look for those, you'll be able to execute your code.
$("input[name='HearAboutUs']").click(function() {
var clicked = $(this).val(); //save value of the input that was clicked on
if(clicked == 'Agent'){ //check if that val is "Agent"
$('#AppliedCourse').hide();
}else{
$('#AppliedCourse').show();
}
});
JS Fiddle Demo
Another option as suggested by #Regent is to replace the if/else statement with $('#AppliedCourse').toggle(clicked !== 'Agent');. This works too.
Here is the Fiddle: http://jsfiddle.net/L9bfddos/
<tr>
<td class="text">
<input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other
</td>
Test
$("input[name='HearAboutUs']").click(function() {
var value = $('input[name=HearAboutUs]:checked').val();
if(value === 'Agent'){
$('#AppliedCourse').hide();
}
else{
$('#AppliedCourse').show();
}
});

Change an onclick value with javascript

I'm pretty new to JS and maybe this is a very banal questions but I still can't figure out what's wrong. I have this simple html code:
<span>1</span>
<input id="check1" type="radio" value="a1"/>
<span>2</span>
<input id="check2" type="radio" value="b2"/>
<span>3</span>
<input id="check3" type="radio" value="c3"/>
<span>4</span>
<input id="check4" type="radio" value="a4"/>
<span>5</span>
<input id="check5" type="radio" value="b5"/>
<input id="red" type="button" value="Go" onclick=""/>
What i would like to achieve is, based on the radio checked change the onclick property.
For example, if check1 and check2 are checked go to google.com, if check1 and check3 go to jsfiddle.net etcetera. So I wrote a simple Javascript:
window.onchange = function redirect(){
if (document.getElementById('check1').checked && document.getElementById('check2').checked) {
location.href='www.google.com';
// document.getElementById('red').onclick="www.google.com"
}
else if (document.getElementById('check1').checked && document.getElementById('check3').checked) {
location.href='www.jsfiddle.net';
// document.getElementById('red').onclick="window.open('www.jsfiddle.net')"
}
}
Here You can find a JS Fiddle.
What I thought to do was to set the onclick property like I did with an image, using getElementById and then setting his source, so I wrote document.getElementById('red').onclick="window.open('random page')" but for some reason that I can't understand it doesn't work.
Questions:
1) As you can see in my code i wrote a location.href='address' that obviously doen't wait for the user to click the button, so that's not a solution, how can I make this work?
2)Is there a way to make this piece of code more scalable? What I mean is, in the future if I want to add another radio, I would have to modify manually the code and insert another else if, I thought about something like:
var radio = document.getElementByName('radio') //not sure if this is the right getElement
for (var i=1; i<radio.lenght; i++){
if radio[i].checked{ //is this right?
for (var n=i+1; n<radio.lenght; n++){
if radio[n].checked{
document.getElementById('red').onclick="window.open('random page')"
}
}
}
Any suggestion to my code is welcome.
​
Try out this in JS Fiddle. It contains how you can listen the onclick event of a button and to get the checked value of a radio button.
HTML part:
<form action="">
<input type="radio" name="vehicle" value="Yes" id='yes'>Yes<br>
<input type="radio" name="vehicle" value="No" id='no'>No
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
if (document.getElementById('yes').checked) {
alert('I have a Vehicle.');
} else if(document.getElementById('no').checked) {
alert('I don\'t have a Vehicle.');
} else {
alert('No answer.');
}
}
If you use radio buttons, and you want only one to be selectable to the user at a time you have to set the same name attribute to them.
You can also make use of the value property of radio buttons for storing the redirection URL.
Here is a more useful example for you.
HTML part:
<form action="">
<input type="radio" name='redirect' value='https://www.google.com/' id='google'>Google<br />
<input type="radio" name='redirect' value='http://www.jsfiddle.net/' id='jsFiddle'>JS Fiddle<br />
<input type="radio" name='redirect' value='https://www.facebook.com/' id='Facebook'>Facebook
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
var options = document.getElementsByName('redirect'),
length = options.length,
i = 0;
for (i; i < length; i++) {
if (options[i].checked) {
window.open(options[i].value);
}
}
}
if (document.getElementById('check1').checked&&document.getElementById('check2').checked)
{
document.getElementById('red').onclick=function(){
window.location.href ='http://www.google.com';
};
}
This code binds the function to the onclick event of element with id='red'. So add a bunch of such conditions and change the onclick binding whenever any radio button is checked/unchecked.

Getting the selected radio without using "Id" but "name"

I was trying to get selected radio button by using "document.getElementByName('nameOfradio')" because all of the radio buttons share the same name. But, nothing happened. I tried the same thing with document.getElementById('nameOfradio') and worked well.However, I had to give unique id for all of the radio buttons. So that, it turns ugly when i have 20 radio buttons. As a result, what I wanted is making a shortcut. How can i get the value of selected radio button by using their "name"? Codes;
Html
<input type="radio" name="nameOfradio" value="onm1" /> 1
<input type="radio" name="nameOfradio" value="onm2" /> 2
<input type='button' onclick='radio3()' value='Submit' />
</form>
Ajax(relavant part of radio3())
var radioPushed = document.getElementByName('nameOfradio').value;
var queryString = "?radioPushed=" + radioPushed;//to send the value to another file
ajaxRequest.open("GET", "radio_display.php" + queryString, true);
ajaxRequest.send(null);
As i said document.getElementById worked but it requires too much work:( How can i make it simplier by using common feature of radio buttons, instead of giving them unique id? A short explanation why i could not make it would be very helpful(new in javascript and ajax)
This line:
document.getElementByName('nameOfradio').value
should be:
document.querySelector('input[name=nameOfradio]:checked').value;
using querySelector
Note that CSS pseudo-classes are accessed by a colon (:).
document.querySelector('input[name=nameOfRadio]:checked').value
Eg:-
<form>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
document.querySelector('input[name=gender]:checked').value
Also, you can add a checked attribute to a default radio button among the group of radio buttons if needed
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
Save yourself some pain in the later js dev and use a js library like jQuery. Then you can do something like $('input[name=radioName]:checked').val()
This is exactly why you should use a javascript library.
document.querySelector('input[name=nameOfradio]');
for example is not supported before IE8.
Let the library handle the browser craziness.
In jQuery you can just use $('input[name=radioName]:checked').val() or $("form").serialize() and be done with it.
You can use the class property if your looking for a quick solution. Many elements can have the same class. use the command:
document.getElementsByClass('nameOfradio');
In addition you should use the correct form of getting elements by name which is:
document.getElementsByName('nameOfradio');
You can also use the following code to find the selected radio value as follows:
radioObj=document.getElementsById('nameOfradio');
var radioLength = radioObj.length;
if(radioLength == undefined) {
if(radioObj.checked) {
return radioObj.value;
} else {
return "";
}
}
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";

Radio button required - JavaScript validation

I know nothing of JavaScript.
I had to add a group of two radio buttons to an HTML form with values "yes" and "no".
Now I need to make them "required"
There are several other required fields in the form and this piece of JavaScript:
<SCRIPT LANGUAGE="JavaScript">
<!--
reqd_fields = new Array();
reqd_fields[0] = "name";
reqd_fields[1] = "title";
reqd_fields[2] = "company";
reqd_fields[3] = "address";
reqd_fields[4] = "city";
reqd_fields[5] = "state";
reqd_fields[6] = "zip";
reqd_fields[7] = "phone";
reqd_fields[8] = "email";
reqd_fields[9] = "employee";
function validate(form_obj) {
if (test_required && !test_required(form_obj)) {
return false;
}
It was done by someone else, not me.
What I did is just added my field to this array, like this:
reqd_fields[10] = "acknowledge";
However it doesn't seem to be working.
Please guide me as I am totally ignorant when it comes to JavaScript.
Why don't you just make one selected by default then one will always be selected.
A link to your page or a sample of your HTML would make this easier, but I'm going to hazard a guess and say that the values in the array match the "name" attribute of your radio button elements.
If this the case, "acknowledge" should be the name of both radio buttons, and to make things easier, one should have the attribute "checked" set to "true" so there is a default, so you'll get a value either way.
So, something like this:
<input type="radio" name="acknowledge" value="yes" /> Yes <br/>
<input type="radio" name="acknowledge" value="no" checked="true" /> No <br/>
I know question is ancient but this is a simple solution that works.
<script type="text/javascript">
function checkForm(formname)
{
if(formname.radiobuttonname.value == '') {
alert("Error: Please select a radio button!");
return false;
}
document.getElementById('submit').value='Please wait..';void(0);
return true;
}
</script>
<form name="formname" onsubmit="return checkForm(this)"
<input type="radio" value="radio1" name="radiobuttonname" style="display:inline;"> Radio 1<br>
<input type="radio" value="radio2" name="radiobuttonname" style="display:inline;"> Radio 2<br>
<input type="submit" value="Submit">
</form>
Without seeing your HTML and more context of your validate function it's unclear exactly what you're looking for, but here's an example of how to require a selected value from a radio group:
<form name="form1">
<input type="radio" name="foo"> Foo1<br/>
<input type="radio" name="foo"> Foo2<br/>
</form>
<script type="text/javascript">
var oneFooIsSelected = function() {
var radios = document.form1.foo, i;
for (i=0; i<radios.length; i++) {
if (radios[i].checked) {
return true;
}
return false;
};
</script>
Here is a working example on jsFiddle.
I always recommend using jQuery validate seems better to me than trying to re-invent the wheel

Categories