I'm trying to build a simple feedback form. The user will answer a series of yes or no questions. If they choose no, then they will be provided with a comment form to include text.
Currently, I'm having problems with retrieving radio button values. I am trying to print them in the console, but nothing happens when I choose the appropriate choice. If the user chooses 'no', it needs to be able to remember the comment that will get submitted.
My JSFiddle is here: http://jsfiddle.net/787x18vx/
HTML
<p>You are providing feedback</p>
<form>
<div id="question-1">
<label for="question-1">Is this correct?</label>
<input type="radio" value="yes" name="choice-1" />Yes
<input type="radio" value="no" name="choice-1" />No
</div>
<div id="question-2">
<label for="question-2">Another question</label>
<input type="radio" value="yes" name="choice-2" />Yes
<input type="radio" value="no" name="choice-2" />No
</div>
<div id="question-3">
<label for="question-3">One more question</label>
<input type="radio" value="yes" name="choice-3" />Yes
<input type="radio" value="no" name="choice-3" />No
</div>
<br />
<button>Send Feedback</button>
</form>
jQuery
var firstInput = 'input[name=choice]';
var firstInputValue = $('input[name=choice-1]:checked').val();
$(firstInput).on('click', function() {
console.log(firstInputValue);
console.log($('input[name="choice-1"]:checked').val());
console.log($('input[name="choice-2"]:checked').val());
// if value === 'no' show comment form
});
You are using input[name=choice] selector which is not exisiting.
Use input[type=radio] instead.
var firstInput = 'input[type=radio]';
var firstInputValue = $('input[name=choice-1]:checked').val();
$(firstInput).on('click', function() {
console.log(firstInputValue);
console.log($('input[name="choice-1"]:checked').val());
console.log($('input[name="choice-2"]:checked').val());
// if value === 'no' show comment form
});
Fiddle
var firstInput = 'input[name=choice]';
This is looking for something specifically with the name choice, which doesn't appear to be in your html.
There are two quick ways about this.
First, just change your selector:
$('input[type=radio]').on('click', function(){...
This will trigger the function on a click of any radio
Another way is with the wildcard selector:
var firstInput = 'input[name^=choice]';
The ^ should make is so any input with the name starting with choice gets selected.
This method should work, but targeting input[type=radio] is probably a better solution,
You are missing the -1 in your name
var firstInput = 'input[name=choice-1]';
Your selector is trying to get tags with name exactly equals 'choice'. You can search by prefix with the following
var firstInput = 'input[name|="choice"]';
This will get all tags which name starts with 'choice'
Related
I'm having problems getting the radio button value when the form is submitted. I thought that when the form is submitted it would get the final selection that user made but it appears it doesn't recognize which one is selected.
On initial load: This is inside my form
<div id="question1">
<label> Do you shop mostly on-line or at physical stores? </label>
<div class="radioButtons">
<span>
Mostly on-line stores
<input name="question1" value="on-line" type="radio">
</span>
<span>
mostly physical stores
<input name="question1" value="physical" type="radio">
</span>
<span>
About both equaly
<input name="question1" value="both" type="radio">
</span>
</div>
</div>
in my submit handler
$(".aboutmeQuestions").on("submit", function(e){
e.preventDefault();
var values = {};
var $inputs = $(".aboutmeQuestions :input").not(":submit");
$inputs.each(function(){
values[this.name] = {answer : $(this).val()};
});
//I thought the above would get the radio buttons but I think it got the last choice as the selected one no matter what was chosen. so I tried below because I thought that the checked attribute would change automatically.
$("input[type='radio']").each(function(){
console.log("this ",this);
if($(this).attr("checked")){
values[this.name] = {answer : $(this).val()};
}
})
In my EJS:
<div id="question1">
<label> <%=aboutUser.question1.question%> </label>
<div class = "radioButtons">
<span>Mostly on-line stores <input type="radio" name="<%=aboutUser.question1.name%>" value="on-line" <% if(aboutUser.question1.answer == "on-line"){%> checked <%}%>> </span>
<span>mostly physical stores <input type="radio" name="<%=aboutUser.question1.name%>" value="physical" <% if(aboutUser.question1.answer == "physical"){%> checked <%}%>> </span>
<span> About both equaly <input type="radio" name="<%=aboutUser.question1.name%>" value="both" <% if(aboutUser.question1.answer == "both"){%> checked <%}%> ></span>
</div>
</div>
I tested it out. After clicking on nothing and pressing the submit button I get for values object, question5[answer]: maybe" question1[answer]: "both" that should of been equal to nothing. It is always like that no matter what I click. I don't like that pleas help me fix it. I didn't think I have to use a change method.
Ps I save this data to DB and the inputs should be populated with answers so when I reload the page <span>
About both equaly<input name="question1" value="both" checked="" type="radio">
</span>. it shouldn't have been checked since I didn't select anything.
First, remove the checked attribute from all the checkboxes unless there is ONE that you want to be pre-selected and in that case add it to just that ONE.
There is no need to loop through the radio buttons to see which was checked. Just use the :checked pseudo-class. Change this:
$("input[type='radio']").each(function(){
console.log("this ",this);
if($(this).attr("checked")){
values[this.name] = {answer : $(this).val()};
}
})
to this:
var checkedRad = $("input[type='radio']:checked");
values[this.name] = {answer : checkRad.value};
or, if you don't need a reference to the checked radio button after getting its value::
values[this.name] = {answer : $("input[type='radio']:checked")};
$("input[type=radio]").on("click", function(e){
console.log($("input[type='radio']:checked").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="question1">
<label> Do you shop mostly on-line or at physical stores? </label>
<div class="radioButtons">
<span>
Mostly on-line stores
<input name="question1" value="on-line" type="radio">
</span>
<span>
mostly physical stores
<input name="question1" value="physical" type="radio">
</span>
<span>
About both equaly
<input name="question1" value="both" type="radio">
</span>
</div>
</div>
I need to store in my js file which radio option for each radio name was selected as well as store the Username that was entered. Here is my form
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input type="radio" name="class"/>Archer
<input type="radio" name="class"/>Mage
<input type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input type="radio" name="race"/>Orc
<input type="radio" name="race"/>Elf
<input type="radio" name="race"/>Human
<input type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
EDIT:
When I try to target the submit button for a click function it causes my page to reload instead of making the form fadeOut
var userInput;
var classInput;
var raceInput;
$('input[type=submit]').click(function(){
$('#newPlayer').fadeOut(500);
userInput = $('input[name="user"]').val();
classInput = $('input[name="class"]:checked').val();
raceInput = $('input[name="race"]:checked').val();
});
Maybe this helps. First, you will have to put values on those inputs
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input value="archer" type="radio" name="class"/>Archer
<input value="mage" type="radio" name="class"/>Mage
<input value="warrior" type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input value="orc" type="radio" name="race"/>Orc
<input value="elf" type="radio" name="race"/>Elf
<input value="human" type="radio" name="race"/>Human
<input value="worg" type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
Then, using jQuery, a simple .val() will do the job:
var class_val = $('input[name="class"]:checked').val();
var race = $('input[name="race"]:checked').val();
var user = $('input[name="user"]').val();
After that, you just need to put in localStorage
localStorage.setItem('class', class_val);
localStorage.setItem('race', race);
localStorage.setItem('user', user);
To access those values in the future, you do that
var stored_class = localStorage.getItem('class');
var stored_race = localStorage.getItem('race');
var stored_user = localStorage.getItem('user');
To make things happens on submit, you add an submit event to the form, like that:
$('form').on('submit', function() {
// Get values
var class_val = $('input[name="class"]:checked').val();
...
// Store values
localStorage.setItem('class', class_val);
...
// Avoid form submit
return false;
});
Hope it helps :)
I think I would use localStorage.
For example:
//Make sure to set the selection variable to a object that contains the selections made by the user.
function save() {
//This will save the current settings as an object to the localStorage.
localStorage.selections = JSON.stringify(selections) ;
}
function load() {
if (!localStorage.selections) {
alart("No saves found.") ;
return false ;
}
selections = JSON.parse(localStorage.selections) ;
}
Read more about localStorage here.
So I have a kind of problem: I need to remove "information" from tag to tag including text between it.
So somewhere in html is:
<input type="radio" rel="1" value="Surname1" name="lastnames">Surname1<br>
<input type="radio" rel="2" value="Name2" name="lastnames">Name2<br>
<input type="radio" rel="3" value="lol" name="lastnames">lol<br>
<input type="radio" rel="4" value="lol2" name="lastnames">lol2<br>
And for example:
var current_id = $('input:checked:radio').attr('rel');
$.get('index.php?delete_by_id='+current_id);
$("input:radio[rel='"+current_id+"']").remove();
So, after the GET to php is sent, I need to delete from the radio list deleted item. With input all ok, but with name next to him I have problems...
PS.
I know, that situation is stupid, but I don't have any time to rewrite it until tomorrow (exams)
Wrap the label with a span element.
<input type="radio" rel="1" value="Surname1" name="lastnames"><span>Surname1</span><br>
<input type="radio" rel="2" value="Name2" name="lastnames"><span>Name2</span><br>
Then while deleting, Get the next span and remove it as well
var item=$('input:checked:radio');
var current_id = item.attr('rel');
$.get('index.php?delete_by_id='+current_id,function(data){
item.remove();
item.next("span").remove();
});
It is always a good practice to keep HttpPost Operations for Delete/Update functions. Otherwise anybody can delete a record from your database if they know the item id, by simply executing your page with those querystrings in the browser.
Not sure exactly what you are trying to do and/or why it is not working, but consider writing the code like this:
var $selected_radio = $('input:radio:checked'); // store element reference
$.get('index.php?delete_by_id=' + $selected_radio.attr('rel'), function() {
// use a callback function to only remove if code succeeds
$selected_radio.remove();
});
EDIT: Looking back I see you want to remove the input along with its label. You just need to fix your HTML to be what it actually should be:
<label>
<input type="radio" rel="1" value="Surname1" name="lastnames"> Surname1
</label>
Which then makes the remove code in jQuery look like:
$selected_radio.closest('label').remove();
I ussually always use a label, to show text that is connected to a radio button:
<input id="radio1" type="radio" rel="1" value="Surname1" name="lastnames"><label for="radio1">Surname1</label><br>
<input id="radio2" type="radio" rel="2" value="Name2" name="lastnames"><label for="radio2>Name2</label><br>
<input id="radio3" type="radio" rel="3" value="lol" name="lastnames"><label for="radio3">lol</label><br>
<input id="radio4" type="radio" rel="4" value="lol2" name="lastnames"><label for="radio4">lol2</label><br>
Then you can do like this in your javascript code:
var current_rel = $('input:checked:radio').attr('rel'),
current_id = $('input:checked:radio').attr('id');
$.get('index.php?delete_by_id='+current_rel);
$('#' + current_id + ', label[for="' + current_id + '"]).remove();
and trying my best to get my head around the jQuery validator plugin.
I have googled extensively, but could not find anything similar to what i am trying to achieve. Please could someone help.
I am trying to build a questionnaire form using radio buttons, and validate them using the jQuery validator plugin.
How would I go about setting the validation rules specific to certain answers being either yes or no values:
<p>Are you a member of our group? <br />
<input type="radio" name="member" value="Yes" class="required" id="memberYes" />
<label for="memberYes">Yes</label> <<<<----User must be a member and select 'Yes'
<input type="radio" name="member" value="No" id="memberNo" />
<label for="memberdNo">No</label>
</p>
<p>Are you currently under investigation? <br />
<input type="radio" name="investigation" value="Yes" class="required" id="investigationYes" />
<label for="investigationYes">Yes</label>
<input type="radio" name="investigation" value="No" id="investigationNo" />
<label for="investigationNo">No</label> <<<<----User must select 'No' or a message pops up to send them to the correct form
</p>
<p>Has your cat turned green? <br />
<input type="radio" name="greenCat" value="Yes" class="required" id="greenCatYes" /> <label for="greenCatYes">Yes</label> <<<<---- User must select 'Yes' This is only for users who's cat's are green
<input type="radio" name="greenCat" value="No" id="greenCatNo" />
<label for="greenCatNo">No</label>
</p>
<p>Are you currently on the diet? <br />
<input type="radio" name="diet" value="Yes" class="required" id="dietYes" />
<label for="dietYes">Yes</label> <<<<----User must select the 'Yes' option.
<input type="radio" name="diet" value="No" id="dietNo" />
<label for="dietNo">No</label>
</p>
I have tried the following methods but none not seem to work:
$('#Form').validate({
rules: {
member:{required: function() {
$('input[name="member"]:checked').val() === 'Yes';
}
},
investigation:{required: function() {
return $('#investigationNo').is(':checked');
}
},
greenCat:{required:true},
diet:{required:'#dietYes:checked'}
}
Kindest Regards, and Thanks in advance for your assistance
I have tried adding a new method, but somehow it does not seem to work.
jQuery.validator.addMethod('correctAnswerRadio', function(value, element) {
var selectedVal = $('input[name='+element+']:checked').val();
alert(element.name + selectedVal + value);
if(selectedVal === value){ //Correct Value
return true;
}else{
return false;
}
});`
i changed this to:
$('#Form').validate({
rules: {
member:{required:true,correctAnswerRadio:'Yes'},
investigation:{required:true,correctAnswerRadio:'No'},
greenCat:{required:true,correctAnswerRadio:'Yes'},
diet:{required:true,correctAnswerRadio:'Yes'}
}
});
The method only alerts 'value' as "Yes" values when correctAnswerRadio:'No'. What could i be doing wrong?
I know it is an old post but google still brings people here.
I've found a simple way to solve it. It's not at the jquery validator's documentation but solved.
First of all you must select one radio. It could be the "No". The value can be any, but I've worked with "True" or "False"
Secondly do this at javascript (assuming your field name is terms)
$('form').validate({
rules:{
terms: {min:"True"}
},
messages:{
terms: {min:'you must accept terms to move on.'}
}
});
I've made an example at jsfiddle: http://jsfiddle.net/ThcS8/117/
Hey i had the same problem, here is a method i used to make it work:
$.validator.addMethod("hasToBeYes", function(value, element) {
var elem_name = $(element).attr('name');
value = $('input:radio[name="'+elem_name+'"]:checked').val();
return(value == 'yes');
}, 'You have to answer "Yes" to this question');
you can just define a second validation method, correctAnswerRadioNo that would check that the radio group has a selected value of 'No', and use it when the 'required' answer is no.
I have managed to solve this in a messy way by having to create a method for every radio button. If someone has a better more efficient way let me know :)
jQuery.validator.addMethod('member', function(value, element, params) {
return $("input[name='member']:checked").val() == 'Yes';
}, "You need to be a member to continue");
jQuery.validator.addMethod('investigation', function(value, element, params) {
return $("input[name='investigation']:checked").val() == 'Yes';
}, "You should not be under investigation to continue");
jQuery.validator.addMethod('greenCat', function(value, element, params) {
return $("input[name='greenCat']:checked").val() == 'Yes';
}, "Your cat must be green to continue");
jQuery.validator.addMethod('diet', function(value, element, params) {
return $("input[name='diet']:checked").val() == 'Yes';
}, "You must be on a diet to continue");
and
rules: {
member:{required:true,member:true},
investigation:{required:true,investigation:true},
greenCat:{required:true,greenCat:true},
diet:{required:true,diet:true}
}
It seems to work well, but the only problem i have now is that the first radio button on first click does not show an error if the incorrect value is selected. after you toggle the radio button selection a bit the correct error appears. could this be a bug?
I had the same problem and I solved it by adding a class "correct" to the specific radio button I want selected, then add a method that checks whether this is checked, and bind the method to the class.
Like this:
<script>
// add new method:
jQuery.validator.addMethod("correct", function(value,element) {
return $(element).is(':checked') ; }, "You must choose this option.");
// bind new method to class "correct":
jQuery.validator.classRuleSettings.correct = { correct:true };
</script>
<html>
<p>Are you a member of our group? <br />
<input type="radio" name="member" value="Yes" class="correct" id="memberYes" />
<label for="memberYes">Yes</label> <<<<----User must be a member and select 'Yes'
<input type="radio" name="member" value="No" id="memberNo" />
<label for="memberdNo">No</label>
<p>Are you currently under investigation? <br />
<input type="radio" name="investigation" value="Yes" id="investigationYes" />
<label for="investigationYes">Yes</label>
<input type="radio" name="investigation" value="No" class="correct" id="investigationNo" />
<label for="investigationNo">No</label> <<<<----User must select 'No' or a message pops up to send them to the correct form
</p>
</html>
<script type="text/javascript">
(function () {
var ButtonGroup = YAHOO.widget.ButtonGroup;
var onCheckedButtonChange = function (p_oEvent) {
};
YAHOO.util.Event.onContentReady("mediaFilterButtonsFieldset", function () {
var oButtonGroup = new ButtonGroup("mediaFilterButtons");
oButtonGroup.on("checkedButtonChange", onCheckedButtonChange);
});
}());
</script>
<div id="resultInfo">
<form id="button-example-form" name="button-example-form" method="post">
<fieldset id="mediaFilterButtonsFieldset">
<div id="mediaFilterButtons" class="yui-buttongroup ie7filter" style="z-index:11;">
<div id="mediaFilterLabel">Go to</div>
<input id="radio1" class="filter_but" type="radio" name="0" value="First" checked rel="0" >
<input id="radio2" class="filter_but" type="radio" name="2" value="Second" rel="2">
<input id="radio3" class="filter_but" type="radio" name="1" value="Third" rel="1">
</div>
</fieldset>
</form>
</div>
These are my YUI buttons. They're just 3 radio buttons turned into "buttons"--literally. My question is this:
After people click the third button, I cannot manually check the first button anymore. How can I manually check "radio1"?
Edit:
According to the official YUI website, there is a method called "set". But I don't know how to use that in this buttonGroup.
The radio buttons must all have the same name attribute in order for them to be grouped together.
Answering your question with the set method. Perhaps this does the trick:
YAHOO.one("#radio1").set("checked",true);
To manually check the radio buttons, it's necessary to have the same name of radio button. Put the same name of radio button and get your result.