I have a form with multiple select fields allowing you to select multiple entries per select.
Each select is named id1[], id2[], id3[] etc.
With Jquery when trying to submit the form can I check if any of the selects haven't had anything selected ?
I've tried this, but the form still submits.
$("#submit").click(function() {
$("select[name^='id']:visible").each(function(index, element) {
if ($(this).val() == "") return false;
});
});
I don't need to know which specific 'id' select hasn't had an option selected, but it would be nice if I did..
Thanks
You can use the filter function to return all selects that have no value selected
var selectsWithNoValue = $("select[name^='id']:visible").filter(function() {
return !this.value.length;
});
Then you can just check the length to see if you have any with no value - and you also have access to those elements
if(selectsWithNoValue.length) { // if there are selects with no value
//do something
}
Also since you're working with a form bind to the submit handler of the form so instead of the click of a button.
So if you want to prevent the form submit you can do
return !selectsWithNoValue.length
Which will return false if there are any selects with no value
FIDDLE
Attach the code to form submit handler instead of submit button's click handler, so you can prevent the form from being submitted.
$("form").submit(function() {
var rtn = true;
$("select[name^='id']:visible").each(function(index, element) {
if ($(this).val() == "") {
console.log(this.id); // id
rtn = false;
return false;
}
});
return rtn;
});
Related
I have a form where small labels are displayed above each field, once the user adds a value to that field.
This for is sometimes loaded with some of the fields being pre-populated.
How would i check on page load if any of the form fields have a value and if so, have the label visible?
Here's my current code for displaying labels once a field has a value:
$('.form-control').blur(function() {
if( $(this).val() ) {
$(this).prev().show();
}
});
on page load try this:
$('.form-control').each(function() {
if( $(this).val() ) {
$(this).prev().show();
}
});
$(document).ready(function(){
$('.form-control').each(function(){
if($(this).val() != ''){
$(this).prev().show();
}
});
});
On document ready, for each .form-control, if the input's value is not blank, do whatever code you would to show the label.
Using focusout Event wouldn't be much of an overkill, would it?
<script type="text/javascript">
(function ($) {
$(document).ready(function (e) {
// ALTHOUGH BLUR IS OK, ONE COULD SIMPLY BIND THE .form-control CLASSES TO THE focusout EVENT
// THIS ENSURES THAT THERE IS A HIGHER LIKELIHOOD THAT THE FIELD IN QUESTION ONCE HAD FOCUS
// WHICH MAY IMPLY THAT THE USER ALSO INTERACTED WITH THE FIELD IN SOME WAY...
$('.form-control').each(function(elem){
var objElem = $(this);
objElem.focusout(function(evt) {
if ($(this).val()) {
// NOW, YOU SHOULD KNOW WHICH METHOD TO USE TO TRAVERSE THE DOM
// AND GET AT THE LABEL....
// IN YOUR CASE IT SEEMS TO BE THE PREVIOUS ELEMENT BEFORE THE FORM-FIELD.
$(this).prev().show();
}
});
});
});
})(jQuery);
</script>
I have a form on my view page.. whenever form populate on the page ..it is filled with old values ... I mean input box and check-box have old values ... and then I am posting form through ajax..after posting if values successfully saved into database I am showing the message that information updated successfully or vice versa...so the problem is now that if for example user do not change anything,the form values are same in the text-boxes then when user pressed save button i don't want to show him that information has updated as he didn't do anything .. I want to ask if that possible in java script ...or should i have to query into the database and check that whether values are same or not? and the other thing that if it can be possible that button remains disable until he do some changes in any of the form field...
I am not writing the whole code just the javascript part
$("#submit").click(function(e){
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password-check').val();
var oldpassword = $('#oldpassword').val();
var timezone = $('#UserinfoTimezone').val();
var alternate_email = $('#alternate_email').val();
//var newsletter = $('#newsletter').val();
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
password: $('#password-check').val(),
oldpassword: $('#oldpassword').val(),
timezone: $('#UserinfoTimezone').val(),
alternate_email: $('#alternate_email').val(),
};
$.ajax({
type:"POST",
data:form_data,
url:"https:/localhost/settings/",
success : function(data) {
alert("successfully data saved"):
}
});
You can save the values while you would have populated the fields in the form... Otherwise you can use a flag variable which can be given a value in .change() function of each field and that value can be checked on submit of the form.. But I guess the first option will be more efficient as the flag will be set even if the user edits the field and enters the same value again...
You can save the old values in the JavaScript and compare them against the current values in the submit handler. If nothing changed, don't POST.
And yes, you can also have the save button disabled initially and attach onChange handlers to the form fields that enable the save button when the contents of those fields change.
On ajax submit copy input values to some attribute, so you know last sent data.
$('#form input').each(function() {
$(this).data('last-ajax-value', $(this).val());
});
When invoking second ajax submit you can check if these values match and make some decision.
var someValueDiffers = false;
$('#form input').each(function() {
if($(this).data('last-ajax-value') != $(this).val())
someValueDiffers = true;
});
if(someValueDiffers)
// Form changed
else
// Form is the same
On the page load you can get all the input element values and hold them in seperate global variables. When you submit the form check the current input values with old one that you have saved. If any one is not equal, user has changed the form and you can submit it.
var init_name = "";
var submit_flag = false;
$(document).ready( function () {
var init_name = $('#name').val();
$("#submit").click(function(e){
var name = $('#name').val();
if(name == init_name) {
// user has not changed
submit_flag = false;
} else {
submit_flag = true;
}
if(submit_flag) {
// call the ajax
}
})
})
One simple way to achieve that. Diseable the submit button. Eneable it if a change is made on the page.
After submit the ajax values you need to clear the input field values.
Place this code instead of your success:
...
success: function(data){
alert("successfully data saved"):
$('#myformid').find('input:text, input:password, input:file, select, textarea').val('');
$('#myformid').find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
You can unset the input values when page gets loaded.
$(document).ready(function(){
$("input").each(function(){
$(this).val() = '';
});
});
I'm developing a quiz that pulls data out of a mysql database, and displays the results as radio buttons. The radio buttons are populated based off of key=>value and generated via a simple forloop. This has been done many times, simple google searching and research will yield all the results needed to accomplish this. The issue that I'm having, or was having (before I decided to just do this with jquery) was when I submit the form it would execute the javascript function to validate whether a button has been selected, but when you select any option other than the first radio button you'd receive the same "make a selection" alert that you would if you had not selected any buttons. Selecting the first radio button would return true and execute the getCheckedValue function call. It seems as though, the script only recognizes that I have one input type and doesn't understand to iterate through the rest of the buttons. I've refactored this function a dozen times, and still have no idea why this doesn't work.
<?php
foreach ($dataReturn as $j => $value){
echo "<input type='radio' class='answer' id='radiobtn' name='radiobtn' value='".$j."'>" .$value." </input><br/>";
}
?>
Above is the loop that generates the radio buttons (just for reference, $dataReturn is the return value of a shuffled associative array. (Which is working as intended)
When the submit button is clicked, it calls the below javascript function.
function isNull(){
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i <= radiobutton.length; i++){
if (radiobutton[i].checked){
return true;
var answer = radiobutton[i].value;
getCheckedValue(answer);//using this just for testing selected value
}else {
alert("Make a selection.");
}
return false;
}
}
I just can't figure out why this doesn't work. As stated above, using jquery this works perfectly.
Your FOR loop: since JS uses zero-based arrays, you can't have <=, otherwise it will look for an index one higher than what you have. Use < instead;
I moved your validation for whether any fields were checked outside the loop to make management easier. It's cleaner this way than worrying about breakout out of loops in the middle of them.
Here:
function isNull() {
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
isChecked = true;
}
}
if ( !isChecked ) {
alert("Make a selection.");
return false;
}
}
I don't know how your form tag looks, but here is what you need to prevent the form from submitting if no radio fields are checked:
<form action="" method="post" onSubmit="return isNull();">
Try the code below. You do not want your alert to fire or return false until after the for loop is finished.
function isNull(){
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i <= radiobutton.length; i++){
if (radiobutton[i].checked){
var answer = radiobutton[i].value;
getCheckedValue(answer);//using this just for testing selected value
return true;
}
}
alert("Make a selection.");
return false;
}
Also, your php code gives all radio buttons the same id. That is bad; doing so violates w3c standards.
I have a form on my page with a dropdown of counties. I want to somehow, with jQuery or PHP say that if a certain county is selected then redirect otherwise process the form.
I've created a fiddle to try and explain...
http://jsfiddle.net/KVjAc/
Just submit the form and use a php header command for the values you want to redirect. That would be the first thing to check in the form processor script.
No need for javascript unless you are using ajax to refresh parts of the page based on the selection.
I hope this helps(if you need a javascript/jquery solution),
$('#selectbox_ID').change( function() {
if($(this).val() == "your country"){
}
});
Do something like:
$(document).ready(function () {
$('#county').on('change', function () {
var value = $(this).val();
if (value == 'cheshire' || value == 'city of london' || value == 'durham') {
window.location.href = 'http://www.google.com/';
}
})
});
EDIT: Also, you need to add values to your option elements: <option value="cheshire">Cheshire</option>
I have a form, and before it submits I want to check some of the input against a database. The idea: 1) submit form, 2) check values, 3) show error or actually submit the form. Example:
$(form).submit(function() {
$.post('check.php', {
values
}, function(res) {
// result I need before submitting form or showing an error
});
return false;
});
Now, it takes some time before I get the result (i.e. not instantly), so I put in the return false at the bottom, preventing the form to submit before I get the $.post results back and do something with it.
Problem: after I get the results from $.post, and everything turns out to be OK, how do I tell the script to go on with submitting the form? If I use submit() it'll just take it back to this check script, creating an endless loop.
You're essentially submitting the form twice, if you did it this way. That seems wasteful. Instead, just prevent the form submission, and handle the values asynchronously (as you already are). From the server, accept the data if it's good and reject it if it's not. There's no need to submit the form if you're already sending the data to the server to begin with. It's a bit redundant.
You can use a boolean flag for this:
var isValid = false;
$(form).submit(function() {
if (isValid) return true;
$.post('check.php', {
values
}, function(res) {
if (res.valid) {
isValid = true;
$(form).submit();
}
// result I need before submitting form or showing an error
});
return false;
});
Try replacing the submit button with a link that has an onclick. Submit the form programatically afterward. E.g.:
<a id="submit">Submit</a>
$($("a#submit").click(function() {
$.post('check.php', {
values
}, function(res) {
// result I need before submitting form or showing an error
});
if (condition) {
$('[name=form_name]').submit();
};
});