how do i put the following in a for loop - javascript

I would like to put the following in a for loop but i am having difficulties. Any help would be appreciated
$("input:submit").click(function(){
if (!$("input[name=attendance1]").is(":checked")) {
alert('Please select preference');
return false;
}
else if (!$("input[name=attendance2]").is(":checked")) {
alert('Please select preference');
return false;
}
else if (!$("input[name=attendance3]").is(":checked")) {
alert('Please select preference');
return false;
}
});
});
I have tried:
for($i=1; $i<=3; $i++)
{
$("input:submit").click(function(){
if (!$("#food" + $i).is(":checked")) {
alert('Please select preference');
return false;
}
});
});

First fix:
alert('Please select preference);
with
alert('Please select preference');
Then if you want to loop:
for (var i = 0; i < 3; i++) {
if (!$("input[name=attendance" + i + "]").is(":checked")) {
alert('Please select preference');
return false;
}
}
Or better yet use jQuery's startsWith selector:
if (!$('input[name^="attendance"]').is(":checked")) {
alert('Please select preference');
return false;
}
Example

You're missing a closing single quotation mark on all 3 alert statements.

I generally use a class name on my DOM elements when I want to do something like this. That makes it easier to iterate through the elements using .each(). I was not aware of the startsWith selector mentioned above, but it does look a bit cleaner than my method.
<!-- DO STUFF -->
<input name="attendance1" class="my-unique-class-name" />
<input name="attendance2" class="my-unique-class-name" />
<input name="attendance3" class="my-unique-class-name" />
<!-- DO STUFF -->
<script type="text/javascript">
$("input:submit").click(function(){
var valid = true;
$("input.my-unique-class-name").each(function (el) {
if ( ! $(el).is(":checked") ) {
valid = false;
}
});
if ( ! valid ) {
alert('Please select preference');
return false;
}
});
</script>

Here's my take on it. it has the advantage of you listing down in an array what names you want checked, regardless what names they are
//jQuery '.on()' for versions 1.7+
$("input:submit").on('click', function() {
//assume valid unless found otherwise
var valid = true;
//add the input names you want to verify
var nameList = [
'attendance1',
'attendance2',
'attendance3'
];
//loop through names
for (var i = 0; i < nameList.length; i++) {
var checked = $('input[name="'+nameList[i]+'"]').is(':checked');
if (!checked) {
alert('Please select a preference');
//mark false when something wrong found
valid = false;
}
}
//check if validity persisted
if(valid){
//do something
}
//prevent default actions
return false;
});​

Related

Comparing two text box which contains email_Id

Can someone help me out with validation of two text-box with same email Id.
I was able to pop an alert if both the text-box contain the same email Id via JavaScript(my requirement was both text-box cant have same email) but now I m facing a problem if second text box contain more then one email_Id separated my comma(,) the validation doesn't work.
I don't want email that is present in first text box repeat into second text-box.
My code:
<script language="javascript" type="text/javascript">
function validated() {
if (document.getElementById("<%=txtCountry.ClientID %>").value = document.getElementById("<%=txtnewViewer.ClientID %>").value) {
alert("Presenter cant be attende");
return false;
}Else{
return true;
}
}
</script>
check this code out
<script language="javascript" type="text/javascript">
function validated()
{
if (document.getElementById("<%=textbox1.id %>").value == document.getElementById("<%=textbox2.id %>").value)
{
alert("text-box cant have same email");
return false;
}
else
{
alert("Valid");
return true;
}
}
</script>
Can you try this.
var f_email = document.getElementById("f_email").value;
var s_email= document.getElementById("s_email").value;
if(f_email === s_email) {
// do something when email ids are same.
alert("email ids are same");
}
else {
// do something when email ids are same.
alert("email ids are not same");
}
First, you if statement contains an = who always return true and modify your variable (in place of ==).
function validated() {
var clientId = document.getElementById("<%=txtCountry.ClientID %>").value,
viewerId = document.getElementById("<%=txtnewViewer.ClientID %>").value;
if (clientId == viewerId) {
alert("Presenter cant be attende");
return false;
}
return true;
}
After that you can use : Array.indexOf():
var clients = clientId.split(","), viewers = viewerId.split(",");
// Here we have two arrays with all datas
for(var i = 0; i < clients.length; i++){
var k = viewers.indexOf(clients[i]);
if(k !== -1) {
alert(clients[i], "=", viewers[k]);
}
}

javascript skips validation form

I have html running javascript after form,
form name="mortgage" method="post" action=" "onsubmit="return completeFormValidation();">
And javascript code for validation,
function completeFormValidation() {
location();
} // End of completeFormValidation
function location(){
var numradio = document.mortgage.propLocation.length;
var selected="";
for(var i=0; i < numradio; i++){
if(document.mortgage.propLocation[i].checked == true){
selected += "Selected radio item " + i;
}
}
if(selected == ""){
document.getElementById("reserved").innerHTML = "<p> none radio selected </P>";
return false;
}
}
The code works perfectly fine in dream weaver but in browsers doesn't seem to work instead it will submit even if radio buttons aren't selected. Please help me out thanks.
because you are not returning the "FALSE/TRUE" value from completeFormValidation function.. And Change the name of the function Location is reserved by JavaScript.
check the jsfiddle
function completeFormValidation() {
return my_location();
}
its always better to return the value from location true OR false
you can modify your my_location() as below
function my_location(){
var numradio = document.mortgage.propLocation.length;
var selected="";
for(var i=0; i < numradio; i++){
if(document.mortgage.propLocation[i].checked == true){
selected += "Selected radio item " + i;
}
}
if(selected == ""){
document.getElementById("reserved").innerHTML = "<p> none radio selected </P>";
return false;
}
else{
return true;
}
}
try to replace
function completeFormValidation() {
location();
} // End of completeFormValidation
by
function completeFormValidation() {
return location();
} // End of completeFormValidation
Rename your location function. location is a native property of the window object and can not be redefined.

How to disable the button if the input has no arrays?

I have the following in my HTML thing, The input value will be populated by the user selection and store the values in the format of array( 45[45, 6, 33], 67[67,2,5] and so on.. ). Basically the value would be like the following:
<input id="question_string" type="hidden" value="{}">
<input class="submit_updates" name="commit" type="submit" value="Process">
Now i need to disable the submit button or alert some messages like 'Select all values' if the input has no arrays in the {}.
Updated:
var question_hash_element = document.getElementById('question_string');
var question_hash = JSON.parse(question_hash_element.value);
var myArray = new Array();
myArray[0] = window.batch_question_id;
myArray[1] = window.answer_id || window.answer_text || window.batch_answer_checkbox
myArray[2] = window.build_id
This bit of above code store the values into the {}. I just want to disable and let the user to select all the fields to process the form. If the values are {}, the button should disabled. and any of the values inside and it should be enabled.
I have tried like the following:
$('.submit_updates').click(function () {
if ($('#question_string') == {}) {
return false;
alert("Select all the Values");
} else {
return true;
}
});
It's not working..
Any help would be appreciated! Thanks
$('.submit_updates').on('click', function (e) {
e.preventDefault();
if ( $.trim($('#question_string').val())=='{}' ) {
alert('no question !');
}else{
this.form.submit();
}
});
You are returning false before alerting the message.
Try this:
$('.submit_updates').on("click", function () {
if ($('#question_string').val() == "{}") { //Adjusted condition
//Alert message
alert("Select all the Values");
//Disable the submit button
$(".submit_updates").prop("disabled", true);
return false;
} else {
return true; //Not really needed
}
});
It is nicer to use on and prop instead of click and attr, as #adeneo suggests.
Try this
$(function(){
$('.submit_updates').on('click', function () {
if ($('#question_string').val() == "{}") {
$(this).prop('disabled', 'disabled');
alert("Select all the Values");
} else {
}
});
});
DEMO

jquery custom validation script without plugin?

i used to use jquery validation plugin but because of lack of this plugin with wysiwyg plugins i wrote a simple script to validate my form
i tried to do it like this
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article body</li>');
return false;
}
if ($('#ArticleTitle').val() == 0) {
$('#errors').show();
$('#errors').append('<li>please enter your article title</li>');
return false;
}
$('#errors').hide();
return true ;
}
i found to 1 problem when it validate the form it's validating it field by field so the errors messages doesn't appear at once
i tried to do something like
var errors = [];
function validateArticle(formData, jqForm, options) {
$('#errors').empty();
if ($('#editor').val() == 0) {
errors.push('<li>please enter your article body</li>');
var invalid = 1 ;
return false;
}
if ($('#ArticleTitle').val() == 0) {
errors.push('<li>please enter your article title</li>');
var invalid = 1 ;
return false;
}
if(invalid == 1){
$.each(errors , function(i, val) {
$('#errors').append(errors [i]);
});
}
$('#errors').hide();
return true ;
}
i tried to push errors as array elements and loop through them in case of invalid is true
bu this one doesn't work at it all ?
is there any way to make it work ?
if ($('#editor').val() == 0) // This is checking if value is 0
This does not make sense..
Try
if ($('#editor').val() == '') //Instead check for empty string
EDIT
Also you seem to be hiding the error's div in the end.
$('#errors').hide();
Try this code Instead
$('#validate').on('click', function() {
var errors = [];
var html = '<ul>' ;
valid = true;
$('#errors').empty();
if ($('#editor').val() == '') {
errors.push('<li>please enter your article body</li>');
valid = false;
}
if ($('#ArticleTitle').val() == '') {
errors.push('<li>please enter your article title</li>');
valid = false;
}
if (!valid) {
html += errors.join('') + '</ul>'
$('#errors').append(html);
}
else{
$('#errors').hide();
}
return valid;
});​
DEMO

JQuery condition with blank input

I need to do multiple checks in a jquery condition ...
I am looking for something like this:
IF checkbox_A is Checked then
If input_A is empty then alert('input_A is Required')
else Add a class="continue" to the div below.
<button id="btn1">Continue</button>
Possible?
I normally wouldn't do this as you haven't even shown an attempt to write any code yourself, but I'm in a good mood.
if ($("#checkboxA").is(":checked")) {
if ($("#inputA").val() == "") {
alert("input_A is required");
}
else {
$("#btn1").addClass("continue");
}
}
$(document).ready(function() {
if($("#yourCheckBoxId").is(":checked")) {
if($("#yourInputId").val() == "") {
alert("empty");
}
else {
$("button[id='btn1']").addClass("continue");
}
}
});
yes, it's possible:
$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');
if (checkBoxA.checked())
{
if (textBoxA.val() == "")
{
$('#btn1').removeClass('continue');
alert("No value entered");
textBoxA.focus();
}
else {
$('#btn1').addClass('continue');
}
} else {
$('#btn1').addClass('continue');
}
});
Maybe
if ( document.getElementById('checkbox_A').checked ){
if (document.getElementById('input_A').value == ''){
alert('input_A is Required')
} else {
$('#btn1').addClass('continue;);
}
}
But if you have multiple elements you want to validate you can avoid manual checking of each field and automate by adding an required class to the element that are required..
<input type="text" name="...." class="required" />
now when you want to validate the form you do
// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
// get their names
var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
// inform the user
alert('The fields \n\n' + fieldnames + '\n\n are required');
// focus on the first empty one so the user can fill it..
fail.first().focus();
}
Demo at http://jsfiddle.net/gaby/523wR/

Categories