I have the following radiocontrols with Default checked to "All". If user checks some other radio button and submits, on postback i want to retain the checked button, so users can see what they clicked..How do I keep whatever was selected using jquery?? i am using is:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var url = 'http://mysite.com/events/Pages/default1.aspx?kwd=';
$(".SearchBoxAndChoices a.searchButton").click(function() {
var radioVal = $("input[name='EventType']:checked").val();
var keywords = encodeURIComponent($(".BasicSearchInputBox").val());
url =url+keywords+"&type="+radioVal;
window.location.href=url;
});
});
</script>
<div class="EventRadios" style="color:#574319; font:13px Trebuchet">
<input type="radio" name="EventType" value="" checked="checked"/>All
<input type="radio" name="EventType" value="Classes" />Class
<input type="radio" name="EventType" value="Events" />Event
<input type="radio" name="EventType" value="Support Groups" />Support Group <br /><br />
</div>
<input name="KeywordBox" class="BasicSearchInputBox" type="text" value="Keyword Search..."/>
<div class="searchBtnHolder"><a class="searchButton" href="#" type="submit"><span>Search</span></a></div>
Here's a quick way:
var value = window.location.href.match(/[?&]type=([^&#]+)/) || [];
if (value.length == 2) {
$('input[name="EventType"][value="' + value[1] + '"]').prop('checked', true);
}
Here's a demo: http://jsfiddle.net/agW9g/
If your server page doesn't redirect somewhere else usually the content is the same. Oh, you can use the server controls and keep the state of the control in the ViewState.
Related
I have a questionaire website, that has about 30 qustions, the website is such that it, displays one question at a time.You only go to the next question when you press the next button.
I have a problem, when I click the next button, the form automatically sends submits the form to the php_script, which then submits the data to the database,
Below is the jquery file that enbales the form to show one question at a time. But the problem is when the next button(which is within the form element) is clicked, the form submits, even when the other mandatory fields are empty.
On the database I end up having the first response and the rest are null or zeros
I would greatly appreciate your efforts in helping me.I do not know what to do now
var q = 1;
$(document).ready(function() {
var selectedOption = $('input[name=options]:checked').val();
$(".questions").hide();
$("#question1").show();
$("#next").click(function() {
$("#question" + q).hide();
q = q + 1;
if(q > 30) {
$("#next").remove();
$("body").append("<input type='submit' value='Submit'>");
} else {
$("#question" + q).show();
}
});
if ((selectedOption == '')){
e.preventDefault();
}
});
Your current validation code is within:
$(document).ready(...)
Which executes at soon as the browser has parsed all the HTML. That is not the correct time to validate form elements.
You need to have this logic in your <form> element's submit event so that you can validate the form elements at the right time and then your e.preventDefault() will potentially cancel the submit event.
Additionally, don't set variables equal to the value of a property of your HTML elements, as you are doing with this line:
var selectedOption = $('input[name=options]:checked').val();
Because this will store just the value of the element at that moment in time. When the value changes later, your variable won't have that data.
Even if you had these things correct, your actual event cancellation code of:
e.preventDefault();
Wouldn't work because you have not captured the event object reference as an event handling function argument. e would be undefined.
This is more of the structure you should be using (see comments inline for details):
var q = 1;
$(document).ready(function() {
$(".questions").hide();
$("#question1").show();
$("#next").click(function() {
$("#question" + q).hide();
q++;
if(q > 30) {
$("#next").remove();
$("body").append("<input type='submit' value='Submit'>");
} else {
$("#question" + q).show();
}
});
// Set up the form's submit event handler. If you want to access the
// event within that function, you need to set up the function to
// bind the event to an event argument (e in this case).
$(form).on("submit", function(e){
var selectedOption = $('input[name=options]:checked');
// Do your validation
if ((selectedOption.val() == '')){
e.preventDefault(); // Cancel the current event
e.stopPropagation(); // Stop the current event from propagating
}
});
});
I re-invented the wheel a bit, the original code was a bit vague on the html aspect, so I splurged and wrote how I would accomplish something similar with heavy reliance on jQuery and event handlers. Also no submit buttons, handle that with jQuery.
Index.html
$(function() {
// Namespace to not pollute, be good to your browser environment, but still allow access from the outside
window.QUESTIONS = window.QUESTIONS || {};
// Save references, because it's not my memory, but my time
QUESTIONS.form = $('#questionForm')
// Disable everything from the start
QUESTIONS.next = $('#next').prop('disabled', true);
QUESTIONS.previous = $('#previous').prop('disabled', true);
QUESTIONS.complete = $('#complete').prop('disabled', true);
// We start at 1
QUESTIONS.position = 1;
QUESTIONS.max = 3; // Could compute this with jquery, but this is an example
QUESTIONS.current = undefined; // The current question jquery reference
// Never auto submit, but we have a way around this ;)
QUESTIONS.form.submit (function() {
return false;
});
// Hide everything
$(".question", QUESTIONS.form).hide();
function checkButtons() {
var checked = QUESTIONS.current && $('input[type=radio]:checked', QUESTIONS.current).length == 1;
// Complete
if (checked && QUESTIONS.position == QUESTIONS.max) { // Only check if set
QUESTIONS.complete.prop('disabled', false);
} else {
QUESTIONS.complete.prop('disabled', true);
}
// Next
if (checked && QUESTIONS.position < QUESTIONS.max) { // Only check if set
QUESTIONS.next.prop('disabled', false);
} else {
QUESTIONS.next.prop('disabled', true);
}
}
function activateQuestion(position) {
// Hide the old question
if (QUESTIONS.current) {
QUESTIONS.current.hide();
}
// Save the position
QUESTIONS.position = position - 0;
// Save the reference
QUESTIONS.current = $('.question[questionIndex=' + QUESTIONS.position + ']', QUESTIONS.form).show();
// Can we go back?
QUESTIONS.previous.prop('disabled', !(QUESTIONS.position > 1));
// setup buttons
checkButtons();
}
QUESTIONS.form.on('click', 'input[type=radio]', function(){
// When I check something, work on buttons
checkButtons();
});
// Stop enter from submitting
$('.question input[type=radio]', QUESTIONS.form).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
}
});
// Next event
QUESTIONS.next.click(function() {
activateQuestion(QUESTIONS.position + 1)
});
// Previous event
QUESTIONS.previous.click(function() {
activateQuestion(QUESTIONS.position - 1)
});
QUESTIONS.complete.click(function(){
QUESTIONS.form[0].submit();
});
// Show the first
activateQuestion(1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="somewhere.php" id="questionForm" method="POST">
<div class="questions">
<div class="question" questionIndex="1">
<h1>Question Title 1</h1>
<p>
<input type="radio" name="question1" id="question1_1" value="A"/> <label for="question1_1">Answer A</label>
</p>
<p>
<input type="radio" name="question1" id="question1_2" value="B"/> <label for="question1_2">Answer B</label>
</p>
<p>
<input type="radio" name="question1" id="question1_3" value="C"/> <label for="question1_3">Answer C</label>
</p>
</div>
<div class="question" questionIndex="2">
<h1>Question Title 2</h1>
<p>
<input type="radio" name="question2" id="question2_1" value="A"/> <label for="question2_1">Answer A</label>
</p>
<p>
<input type="radio" name="question2" id="question2_2" value="B"/> <label for="question2_2">Answer B</label>
</p>
<p>
<input type="radio" name="question2" id="question2_3" value="C"/> <label for="question2_3">Answer C</label>
</p>
</div>
<div class="question" questionIndex="3">
<h1>Question Title 3</h1>
<p>
<input type="radio" name="question3" id="question3_1" value="A"/> <label for="question3_1">Answer A</label>
</p>
<p>
<input type="radio" name="question3" id="question3_2" value="B"/> <label for="question3_2">Answer B</label>
</p>
<p>
<input type="radio" name="question3" id="question3_3" value="C"/> <label for="question3_3">Answer C</label>
</p>
</div>
<button id="previous">Previous</button>
<button id="next">Next</button>
<button id="complete">Complete</button>
</div>
</form>
EDIT 3:
Modified example to hide previous question so only one question at a time is being shown.
EDIT 2:
As pointed out by Scott Marcus I'll move the event handlers inside .ready
Moved the .next button handler outside the .document.ready handler and also added a .submit form handler so you can handle the form submission right there.
This will help you have a single point of code to manage all your form submission situations (validations, messages, clean up, etc.)
$("[id^='question']").each(function(i){
In the previouse line of code we are checking every question that starts with the name question (it matches question1, question2, question3, question11, questionXX, etc.) and for each one of them we test their value (text entered by the user, if ANY of those questions is empty you will prevent the form submission with e.preventDefault(); if everything is correct you just let them submit the form.
var q = 1;
$(document).ready(function() {
$("[id^='question']").hide();
$("#question1").show();
$("#next").click(function() {
$("#question" + q).show();
q = q + 1;
if(q > 4) {
$("#question" + (q-1)).hide();
$("#question" + q).show();
$("#next").remove();
$("#f1").append("<input type='submit' value='Submit'>");
} else {
$("#question" + q).show();
$("#question" + (q-1)).hide();
}
});
$('#f1').submit(function(e){
//var selectedOption = $('input[name=options]:checked').val();
//if ((selectedOption == '')){
// e.preventDefault();
//}
// Check that all 5 inputs have text
$("[id^='question']").each(function(i){
if($(this).val() == ''){
alert('Question ' + $(this).prop('id') + ' is empty!');
e.preventDefault();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="f1">
<div class="questions">
<input type="text" id="question1" />
<input type="text" id="question2" />
<input type="text" id="question3" />
<input type="text" id="question4" />
<input type="text" id="question5" />
<!--
<input type="text" id="question6" />
<input type="text" id="question7" />
<input type="text" id="question8" />
<input type="text" id="question9" />
<input type="text" id="question10" />
-->
</div>
<input type="button" id="next" value="Next" />
</form>
Hope it helps!
I have some radio buttons on a page, and I need to just identify which one was checked in my JS, based on ID. I'm not sure why this isn't working. Each time, I get the "nothing checked" message in my console. Thanks!
HTML:
<input type="radio" id="aud1">elephant</input>
<input type="radio" id="aud2">prairie dog</input>
<input type="radio" id="aud3">tiger</input>
JS:
var aud;
if (document.getElementById('aud1').checked) {
var aud = document.getElementById('file1');
}else if(document.getElementById('aud2').checked) {
var aud = document.getElementById('file2');
}else if (document.getElementById('aud3').checked){
var aud = document.getElementById('file3');
}
else console.log('nothing checked');
See below. I've added a button to your code that you can click after you have some checked.
Initially, when the page loads, there is nothing clicked. Your JS is ran as soon as the page is built there which is why you were seeing the nothing clicked.
document.getElementById('check-radios').onclick = function() {
var aud;
if (document.getElementById('aud1').checked) {
var aud = document.getElementById('file1');
console.log('aud1 checked');
}
else if (document.getElementById('aud2').checked) {
var aud = document.getElementById('file2');
console.log('aud2 checked');
}
else if (document.getElementById('aud3').checked) {
var aud = document.getElementById('file3');
console.log('aud3 checked');
}
else console.log('nothing checked');
}
<input type="radio" id="aud1">elephant</input>
<input type="radio" id="aud2">prairie dog</input>
<input type="radio" id="aud3">tiger</input>
<button id="check-radios">Check for clicked</button>
do you explicitly need this code? why not use a single class, and have the filename/desc as a custom attribute like so:
<input type="radio" name="animals" class="order" data-animal="elephant" />elephant
<input type="radio" name="animals" class="order" data-animal="zebra" />zebra
<input type="radio" name="animals" class="order" data-animal="lion" />lion
<script>
$(".order").click(function () {
var choice = this.getAttribute("data-animal");
alert(choice);
/* console.log(choice); */
})
</script>
That way you dont have to manually keep adding more code, u can just add the html at the top using the same class and a different attribute value... much easier to maintain -
Also since you had an elseif i added a name to group them as individual radios as I presume you intended?
<input type="radio" name="animals" class="order" checked data-animal="zebra">zebra
bear in mind there is no closing tag for input tags - just /> at the end instead of >
I'm working on a little script that will disable a form field if certain radio button are ticked or if the input filed has characters to disable the radio buttons
So what I'm wanting my code to do is when the User enters the text field and adds at least one character of any type to disable the radio buttons and if that field is cleared to re-enable the radio buttons
For some reason when I'm doing either or, my "Enabled" alert keeps showing and the radio buttons aren't being disabled
to get the alert to pop, need to click outside of the input field, I would like this to be a mouseout if possible but I can work on that later
If the value is entered within the form directly, the radio buttons are disabled but I can't get them enabled once the filed is cleared
Steps:
Enter text in text field, if value isn't set in the form. Radio buttons stay disabled
Enter Value within the form, the text buttons stay disabled when the text field is cleared
Working Parts:
If radio btn "Yes" is ticked display "test" string and disable text field
If Radio btn "No" is ticked then enable text field
jQuery version in use: 1.9
Below is my JavaScript and below that is the HTML
Script:
$(function() {
var tlHeader = 'Test';
var f2 = $('#field_2').val();
// This function controls inpput box toggling on/off radio buttons
$( '#field_2' ).change(function() {
if(f2.length != 0) {
alert( "Disabled" )
$("input[name=toggle]").prop('disabled', true)
} else if(f2.length == 0) {
alert( "Enabled" )
$("input[name=toggle]").removeProp('disabled')
};
});
window.invalidate_input = function() {
// This function controls radio btn actions
if ($('input[name=toggle]:checked').val() == "Yes") {
$('#field_2').attr('disabled', 'disabled'),
$('#thgtLdr').html( tlHeader );
$('#thgtLdr').not("No").show();
} else if ($('input[name=toggle]:checked').val() == "No") {
$('#field_2').removeAttr('disabled'),
$('#thgtLdr').not("Yes").hide();
}
};
$("input[name=toggle]").change(invalidate_input);
invalidate_input();
});
</script>
HTML:
<body>
<div id=rdTest>
<div class="inputField">
<label>Focal Image:</label>
<input name="FocalImage" type="text" id="field_2" class='textbox' value="" />
</div> <!-- End input field -->
<div class="radioGroup">
<label>Test Page:</label>
<input type='radio' name='toggle' value='Yes' id="tglyes"/>Yes
<input type='radio' name='toggle' value='No' id="tglno"/>No
</div>
<div id="thgtLdr">
</div>
</div>
</body>
Your use case isnt entirely clear but I'll show you how to achieve the basic goal.
First, I would avoid the mouse events and use keyup with a timer so that my function is only called when the user stops typing and not after each typed letter. Then it's just a mater of checking the text and acting to enable or disable the elements. Here is an example:
var keyupDelay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#field_2').keyup(function() {
var $this=$(this);
keyupDelay(function(){
var val=$this.val();
console.log(val);
if(val=='') $('#tglyes, #tglno').prop('disabled',true);
else $('#tglyes, #tglno').prop('disabled',false);
}, 400 ); // triggered after user stops typing for .4 seconds, adjust value as needed
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=rdTest>
<div class="inputField">
<label>Focal Image:</label>
<input name="FocalImage" type="text" id="field_2" class='textbox' value="" />
</div>
<!-- End input field -->
<div class="radioGroup">
<label>Test Page:</label>
<input type='radio' name='toggle' value='Yes' id="tglyes" disabled="true"/>Yes
<input type='radio' name='toggle' value='No' id="tglno" disabled="true"/>No
</div>
<div id="thgtLdr">
</div>
</div>
Try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click','.choice',function(){
if($(this).val() == 'yes')
{
$('.textfield').prop('disabled',true);
$('#string').html('Test Welcome');
}
else
{
$('.textfield').prop('disabled',false);
$('#string').html('');
}
});
$(document).on('keyup','.textfield',function(){
if($(this).val().length > 0)
{
$('.choice').each(function()
{
if($(this).is(':checked'))
{
$(this).attr('checked',false);
}
$(this).prop('disabled',true);
});
}
else
{
$('.choice').prop('disabled',false);
}
});
});
</script>
<body>
<form>
<input type="text" class="textfield" placeholder="enter text"/>
Yes<input type="radio" name="choice" class="choice" value="yes" />
No<input type="radio" name="choice" class="choice" value="no" />
<p id="string" ></p>
</form>
</body>
You can simplify your code in many ways.
The keyup event will be triggered every time the user releases a key on the text field. Inside the callback, you can get the value of the text field with this.value. From experience, it is best to use .prop() method when toggling certain input-related attributes like disabled and checked. You can enable/disable these attributes using booleans.
// cache the elements to avoid having retrieve the same elements many times
var $textbox = $('#field_2'),
$radios = $('input[name=toggle]'),
$div = $('#thgtLdr');
// everytime user presses a key...
$textbox.on('keyup', function() {
// check if a value was entered or not
// if so, disabled the radio buttons; otherwise enable the radio buttons
$radios.prop('disabled', this.value);
});
// when radio buttons change...
$radios.on('change', function () {
// check if value is Yes or No
if (this.value === 'Yes') {
$textbox.prop('disabled', true);
$div.text(this.value);
} else {
$textbox.prop('disabled', false);
$div.empty();
}
});
<div id=rdTest>
<div class="inputField">
<label>Focal Image:</label>
<input name="FocalImage" type="text" id="field_2" class="textbox" value="">
</div>
<div class="radioGroup">
<label>Test Page:</label>
<input type="radio" name="toggle" value="Yes" id="tglyes">Yes
<input type="radio" name="toggle" value='No' id="tglno">No
</div>
<div id="thgtLdr"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script> // place code here </script>
Also, get into the habit of caching your jQuery objects.
I have 41 checkboxes like this
HTML
<input id="1" type="checkbox" onclick="updatebox()" />
<input id="2" type="checkbox" onclick="updatebox()" />
<input id="3" type="checkbox" onclick="updatebox()" />
<input id="4" type="checkbox" onclick="updatebox()" />
Javascript
<script type="text/javascript">
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
if(document.getElementById('1').checked) {values.push("1");}
if(document.getElementById('2').checked) {values.push("2");}
if(document.getElementById('3').checked) {values.push("3");}
if(document.getElementById('4').checked) {values.push("4");}
textbox.value = values.join(", ");
}
</script>
When checkbox is checked the value is posted in textbox,
now what i want is when the user clicks the checkbox the jquery dialog popups and the user will have two radio buttons with Male or Female options along with ok button so when the user will click on ok the value should be posted on textbox depending on selection M for male F for female along with number like 1M or 1F, 2M or 2F and so on.
P.S user can select multiple checkboxes.
Thanks You!
Here is something that does what you want. HTML:
<body>
<form id="form">
<input id="1" type="checkbox" /> 1
<input id="2" type="checkbox" /> 2
<input id="3" type="checkbox" /> 3
<input id="4" type="checkbox" /> 4
...
<input id="10" type="checkbox" /> 10
...
<input id="41" type="checkbox" /> 41
<input id="list" />
</form>
<div id="prompt" style="display:none;" title="Gender">
<form>
<input type="radio" name="gender" id="radio" value="male" />
<label for="radio">Male</label>
<input type="radio" name="gender" id="radio2" value="female" />
<label for="radio2">Female</label>
</form>
</div>
</body>
The JavaScript:
$(function() {
var form = document.getElementById("form");
var textbox = document.getElementById("list");
var $prompt = $("#prompt");
// We record what is currently checked, and the user's answers in this `pairs` object.
var pairs = [];
// Listen to `change` events.
$("input[type='checkbox']", form).on('change', function (ev) {
var check = ev.target;
if (check.checked) {
// Checked, so prompt and record.
$prompt.dialog({
modal: true,
buttons: {
"Ok": function() {
var gender = $prompt.find("input[name='gender']:checked")[0];
var letter = {"male":"M", "female":"F"}[gender.value];
pairs[check.id] = '' + check.id + letter;
$( this ).dialog( "close" );
refresh();
}
}
});
}
else {
// Unchecked, so forget it.
delete pairs[check.id];
refresh();
}
function refresh() {
// Generate what we must now display in the textbox and refresh it.
// We walk the list.
var keys = Object.keys(pairs);
var values = [];
for (var i = 0, key; (key = keys[i]); ++i) {
values.push(pairs[key]);
}
textbox.value = values.join(", ");
}
});
});
Here is a jsbin with the code above.
Salient points:
This code adds the event handlers using JavaScript rather than use onclick in the HTML. It is not recommended to associated handlers directly in the HTML.
It listens to the change event rather than click. Some clicks can sometimes not result in a change to an input element.
It uses $.dialog to prompt the user for M, F.
The refresh function is what recomputes the text field.
It keeps a record of what is currently checked rather than requery for all the check boxes when one of them changes.
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
for (var i = 1; i <= 41; ++i) {
var id = '' + i;
if (document.getElementById(id).checked) {
var gender = prompt('Male (M) or female (F)?');
values.push(gender + id);
}
}
textbox.value = values.join(", ");
}
A few things to note:
I got rid of all that code repetition by simply using a for loop from 1 to 41.
I also fixed the strange indentation you had there.
You may want to use a method of getting user input other than prompt, but it'll work the same way.
(If you're going to keep using prompt, you might also want to add input validation as well to make sure the user didn't input something other than M or F.)
I have this script which makes possible the insertion of some data using ajax and php.
Now , all works fine, except the radio buttons (the select options work fine as well) , and it takes the first value of the radio buttons..
Why is this happening?
Here is the code:
<div id="formfields" ><label>Tipologia Pdv: </label>
<input type="radio" name="tipologia_pdv" id="tipologia_pdv" value="Iper" style="width:40px;" /><span > Iper</span>
<input type="radio" name="tipologia_pdv" id="tipologia_pdv"
value="Super" style="width:40px;" /><span > Super</span><br /><br /></div>
<div id="formfields" ><label>Richiesta Ccnl: </label>
<input type="radio" name="richiesta_ccnl" id="richiesta_ccnl" value="Si" style="width:40px;"/><span> Si</span>
<input type="radio" name="richiesta_ccnl" id="richiesta_ccnl"
value="No" style="width:40px;"/><span> No</span><br /><br /></div>
The javascript:
// Fetch data from input fields.
var js_tipologia_pdv = $("#tipologia_pdv").val();
var js_richiesta_ccnl = $("#richiesta_ccnl").val();
//let's put all data together
var myData = 'postTipologia_pdv='+ js_tipologia_pdv + '&postRichiesta_ccnl='+ js_richiesta_ccnl + '&postDistretto_pdv=' + js_distretto_pdv + '&postCoopva_pdv=' + js_coopva_pdv + '&postNome_pdv=' + js_nome_pdv;
In php they go something like this:
$postTipologia_pdv = filter_var($_POST["postTipologia_pdv"], FILTER_SANITIZE_STRING);
$postRichiesta_ccnl = filter_var($_POST["postRichiesta_ccnl"], FILTER_SANITIZE_STRING);
Making my comments into an answer:
1) Your id attributes need to be unique.
2) Get the value of the selected radio button using something like: $('input:radio[name=tipologia_pdv]:checked').val();