jquery form check before submit with select name array - javascript

I'm having a hard time with this quick validation i want in place...but i think it's not validating properly because of my select name arrays and i'm not sure how to go about this.
How it should work:
- If stat holiday box is checked for that day && if any Lieu hours are selected for that day give alert error and stop form submission.
My jsfiddle: http://jsfiddle.net/4bgYj/3/
my jquery:
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
var lieuhrs = $(".lieutimehours").val();
$('.lieutimehours').each(function(i, obj) {
if ($("#statholidaycheck").is(":checked") && lieuhrs > 0) {
alert("cannot process: " + lieuhrs);
return false;
}
}
});
});

Let me give you a more user-friendly approach for your problem:
If stat is selected simply disable the form input for lieu hours.
With this you won't have to check anything before submitting the form and the user can't accidentally select a value in lieu hours.
It still needs to be updated to your markup, but the idea is basically:
var stat = $('.stat');
stat.change(function() {
var e = $(this);
var f = e.parent().find('.lieu');
if (e.is(':checked')) {
f.prop('disabled', true);
} else {
f.prop('disabled', false);
}
});
Demo
Try before buy

First, you're missing a );...
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
var lieuhrs = $(".lieutimehours").val();
$('.lieutimehours').each(function(i, obj) {
if ($("#statholidaycheck").is(":checked") && lieuhrs > 0) {
alert("cannot process: " + lieuhrs);
return false;
}
}); // missing ); here. <--------------
});
});
Try it after adding that and you'll find it works for the first checkbox. But select a different checkbox and it will fail. In HTML, you will want to use unique ids to reference an element. What I would do is change your HTML to put a css class on the TR tag, and then look at the contained elements.
<tr class='line'>
<td> <input type='checkbox' class='isHoliday'/> </td>
<td> <select class='lieuHours'>options...</select> </td>
</tr>
and in your script...
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
$('.lines').each(function(i, obj) {
var lieuHours = $(this).find(".lieuHours").val();
if ($(this).find(".isHoliday:checked") && lieuHours > 0) {
alert("cannot process: " + lieuhrs);
return false;
}
}); // missing ); here. <--------------
});
});

You didn't approach the issue properly, the selectors should not be global but specific to the loop you are doing:
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
$('.lieutimehours').each(function(i, obj) {
var lieuhrs = $(this).val();
if ($(this).closest('tr').find('#statholidaycheck').is(":checked") && parseFloat(lieuhrs) > 0) {
alert('works');
return false;
}else{
alert('fail')
}
});
});
});

Related

How made my function affect the DOM Jquery?

Hi, I have written a webSite on Shopify and I want to disable my button and add some customs CSS class to my input if the input is not filled on my 4steps form.
I've written a piece of code with what I remember from Jquery it's been a long time since I've used this language.
This is the jQuery funct:
$(document).ready(function () {
$("#submitButton, #btn0, #btn1, #btn2").click(function () {
ValidateForm();
});
function ValidateForm() {
var invalidForm = false;
var index = 0;
var button = document.querySelector("#submitButton, #btn0, #btn1, #btn2");
$("#form__form--stepForm-" + index + "input.form__form--input").each(function () {
if ($(this).val() < 1) {
invalidForm = true;
}
});
if (invalidForm === true) {
button.disabled = true;
$("input.form__form--input").removeClass(".form__form--validation").addClass(".form__form--validationInvalid");
} else if (invalidForm === false) {
button.disabled = false;
$("input.form__form--input").removeClass(".form__form--validation").addClass(".form__form--validationValid");
index++;
}
}
});
I made all my inputs like this one:
<div class="3/3 3/3--thumb 3/3--pocket grid__cell--center">
<input type="text" id="form__form--lastnameInput" name="contact[lastname]"
class="form__form--input form__form--validation" placeholder="Nom *" value required>
<div class="form__form--invalidFeedback">Veuillez saisir votre nom.</div>
</div>
And the button like this:
<button id="btn0" type="button" class="button button--primary form__form--button"
aria-label="SUIVANT" title="SUIVANT">
{% include 'icon-arrow-slider' %}
SUIVANT
</button>
As you can see it's a very basic function for the jquery and a classic HTML input but it doesn't block the button and doesn't make the CSS work either. I'd like to understand why and how to make it work for this site and the following thanks for your time and help, take care of yourself!
Your value checking is always false, consider using length function instead:
if ($(this).val().length < 1) {
invalidForm = true;
}
You may also need to prevent default behavior of your form. Instead of listening to the click, listen the submit event:
$("#form__form--contactWrapper").on('submit',function (e) {
e.preventDefault(); //the form is not sent yet
ValidateForm();
});
Then at the end of your function ValidateForm you can send it when you have all your needed validations done, like this:
$("#form__form--contactWrapper").submit();
I have get rid of all error by doing a big refacto of my code i share you my code
$(document).ready(function () {
$('[to-step]').on('click', function () {
var to_step = $(this).attr("to-step");
var current_step = $(this).closest('[stepform]').attr("stepform");
var form_error = false;
if (!($(this).hasClass("previous-btn"))) {
$('[stepform="' + current_step + '"] .form__form--input').each(function () {
if ($(this).val().length == 0) {
$(this).addClass("input--error");
form_error = true;
} else {
$(this).removeClass("input--error");
}
});
}
if (!form_error) {
if (current_step < 4 || $(this).hasClass("previous-btn")) {
$('[stepform').hide();
$('[stepform="' + to_step + '"]').fadeIn();
}
}
});
$("#submitButton").on("click", function (event) {
event.preventDefault();
if ($("#form__form--radioRgpd:checked").length == 1) {
$("#contact_form").submit();
} else {
$(".form__form--radioRgpdLabel").addClass("label--error");
}
});
});
this piece of code gonna check at what step i am in my 4 'pages' form and add the proper css class if the form is bad filled or not filled.

Can jquery traverse the entire DOM and find the word Update in a href

Seems that people are clicking on Enter key on board and while I can disable that I have business analysts wanting me to have the Enter key "click" the Update link
Since this is asp.net gridview I don't have a lot of control of it plus there are many rows in which the __doPostBack data is different
How can I detect the word "Update" ( it was "Edit" along with many other rows having that Edit link as well)
Update
Update:
I want to find a keyword in an href that is in a table.
So "Update" is the keyword that is in href which is in a
<table>
<tr>
<td>
<a href..>Update</a>
</td>
</tr>
</table>
Update 2:
Here is a Fiddle
http://jsfiddle.net/bthorn/vzjLzfck/
I believe that this does FIND if update is there
var y = $('a').filter(function(index) { return $(this).text() === "Update"; });
I changed Update to "Updated" and length went from 1 to 0 ....
So then if that is working, I want to then proceed to have that Link executed or whatever do that essentially It is like someone is clicking on that href link
Final working code
$(document).keypress(function (e) {
if (e.which == 13) {
$("a").each(function () {
$("a").filter(function () {
var s = $(this).text() === "Update";
if (s == true) {
//console.log('yes in');
this.click();
}
});
return false;
});
return false;
}
});
If you want to target any href that contains the word "Update" you can use jQuery's filter function on the href
$("a").filter(function(){
return $(this).attr('href').indexOf("Update");
});
If you want the text to contain "Update" you can use:
$("a").filter(function(){
return $(this).text() === "Update";
});
$("body").on("keypress", function(e) {
if(e.which != 13) {
return;
};
$("a").each(function() {
var link = $(this);
if(link.text() == "Update") {
console.log("woot");
window.open(link.attr("href"));
};
});
});

Jquery validation not working properly?

I am trying to do required validation in a asp.net page.
I have multiple controls that will be hidden and displayed.
Controls like checkboxlist,dropdownlist,multiselectedlistbox.
I am using a css class called required attaching to all these controls to check the validation.
I am trying to check if each control has value or not but my code is checking each options with in each controls.
I am really not finding a way not a jquery expert just a novice...
Here is my code any ideas anyone please....
$("input[type='submit']").click(function () {
if ($(this).val() != 'Back') {
var names = [];
var info=" ";
$('.required input').each(function () {
var control = $(this);
if (control.is(':enabled')) {
names[$(this).attr('name')] = true;
}
});
$('.required option').each(function () {
var control = $(this);
if (control.is(':enabled')) {
names[$(this).attr('name')] = true;
}
});
for (name in names) {
var radio_buttons = $("input[name='" + name + "']");
if ((radio_buttons.filter(':checked').length == 0) ||(radio_buttons.filter(':selected').length == 0)) {
info += radio_buttons.closest("table").find('label').html()+"</br>";
}
}
if (info != " ") {
$("#validation_dialog p").html(info);
$("#validation_dialog").dialog({
title: "Validation Error!",
modal: true,
resizable: false,
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
return false;
}
}
});
here is a fiddle for it...
http://jsfiddle.net/bDmgk/35/
I think what you want is:
$(".required input[type='radio']:checked").each(function(){
});
instead of :
$(".required option").each(function(){ ... });
Hi I made some changes to your fiddle basically I checked for the inputs inside each column like this and then I added them to your names array.
Using
$('table.required:eq(0) input:checked')
I you can got all the inputs that are checked on the first column if the lenght of the array returned is 0 then no input is checked, i't the same procedure for the other ones.
An yes those input names are weird.
Check this fiddle
JSFiddle

Filtering html fields with jQuery

I have read about filtering table plugins. What I'm searching for is like this popup window.
(source: staticflickr.com)
When the user starts typing in the search-box, the relevant channel/category (as selected on previous dropdown box) should filter up. Also some animated loading action should happen while the filter process is going on.
I am looking for jQuery plugins which will make my filter-job easier to implement.
I think it is to ambigous to have a plugin for it. Just do something like this:
function filter($rows, category, search) {
$rows.each(function() {
if (category == ($("td:eq(2)", this).text() || category == "all") && (search. === "" || $("td:eq(1)", this).text().indexOf(search) !== -1) {
$(":checkbox", this).removeAttr("disabled");
$(this).show();
}
else
$(this).hide(function(){
$(":checkbox", this).attr("disabled", "disabled");
});
});
}
$("select.category").change(function() {
filter ($(this).closest("form").find("tr"), $(this).val(), $(this).closest("form").find("input.search").val());
});
$("input.search").keyUp(function() {
filter ($(this).closest("form").find("tr"), $(this).closest("form").find("select.catagory").val(), $(this).val());
});
You may need to make a few adjustments in order to make it work with the exact format of html.
Update to make it into a PLUGIN
$.fn.filter_table = function(options) {
options = $.extend(options, {
show: $.noop(), //Callback when a row get shown
hide: $.noop(), // Callback when a row gets hidden
entries: "table tr", // Selector of items to filter.
map: {} //Required parameter
//TODO Add default ajustment parameters here to remove ambiguity and assumptions.
});
return this.each(function() {
var form = this;
function each(callback) {
for (var selector in options.map) {
var check = options.map[selector];
$(selector, form).each(function(){
callback.call(this, check);
});
}
}
function show(row) {
if (!$(row).is(":visible")) {
options.show.apply(row);
$(row).show();
}
}
function hide(row) {
if ($(row).is(":visible"))
$(row).hide(options.hide);
}
function run_filter() {
$(options.entries, form).each(function() {
var row = this, matched = true;
each(function(check) {
matched &= check.call(this, row);
});
matched ? show(this) : hide(this);
})
}
//Bind event handlers:
each(function() {
$(this).bind($(this).is(":text") ? "keyup" : "change", run_filter);
});
});
};
You can use this plugin as follows:
$("form").filter_table({
map: {
//These callback define if a row was matched:
"select.category": function(row) {
//this refers to the field, row refers to the row being checked.
return $(this).val() == "all" || $(this).val() == $("td:eq(2)", row).text();
},
"input.search": function(row) {
return $(this).val() == "" || $(this).val() == $("td:eq(1)", row).text();
}
},
entries: "tr:has(:checkbox)", //Filter all rows that contain a checkbox.
show: function() {
$(":checkbox", this).removeAttr("disabled");
},
hide: function() {
$(":checkbox", this).attr("disabled", "disabled");
}
});
Okay it should work once it was debugged. I haven't tested it. I think that part is up to you.
If your HTML looks like this:
<form id="filterForm">
<input type="text" id="filterBox">
<input type="submit" value="Filter">
</form>
<div id="checkboxContainer">
<label><input type="checkbox" id="checkbox123"> Checkbox 123</label>
</div>
You could do something like...
//Set variables so we only have to find each element once
var filterForm = $('#filterForm');
var filterBox = $('#filterBox');
var checkboxContainer = $('#checkboxContainer');
//Override the form submission
filterForm.submit(function() {
//Filter by what the label contains
checkboxContainer.find('label').each(function() {
//If the value of filterBox is NOT in the label
if ($(this).indexOf(filterBox.val()) == -1) {
//Hide the label (and the checkbox since it's inside the label)
$(this).hide();
} else {
//Show it in case it was hidden before
$(this).show();
}
});
//Prevent the form from submitting
return false;
});
You can use this tablesorterfilter plugin to achieve what you need
Working Fiddle
And also please have a look at http://datatables.net/
There are many options out there. Here is a good place to start: http://www.wokay.com/technology/32-useful-jquery-filter-and-sort-data-plugins-62033.html
Filtering like this isn't incredibly complicated. It may be worth looking at the source of a couple plugins that come close to what you want and then try to write your own. You'll learn a lot more if you do it yourself!

Add class if one select's value is #

$(document).ready(function () {
$("#bcscan").submit(function (e) {
e.preventDefault();
if($("select").val() === '#') {
$(this).addClass("warning");
}
else {
ajaxPost();
}
});
});
I'm using following function, how can I modify it to add class warning, if one of select element's value = "#"?
Currently it's adding warning class to all selects
I think this may be what you want:
$('select').filter(function() {
return ($(this).val() === '#');
}).addClass('warning');
That selects all select elements, filters it down to those elements whose current value is equal to #, then adds the warning class to that subset.
I'll leave my original answer here, though given the changes to the question it's likely no longer relevant. This is my last stab at guessing what it is you want - if this is useful to you, great; if not, oh well.
$(document).ready(function () {
$("#bcscan").submit(function (e) {
e.preventDefault();
var doAjaxPost = true;
$('select').each(function() {
if($(this).val() === '#') {
doAjaxPost = false;
$(this).addClass('warning');
}
});
if(doAjaxPost) {
ajaxPost();
}
});
});
That checks all select elements when the form is submitted - if any of them have a value of # it adds the warning class to that select element. If none of them have a value of # it goes ahead and calls the ajaxPost() function.
$('select').change(function (event) {
if ($(this).val() === '#') $(this).addClass('warning');
});
this is populated with the element that fired the event. In this case the select.
Demo: http://jsfiddle.net/TimWolla/tNhKe/
Edit to match the question:
$(document).ready(function () {
$("#bcscan").submit(function (e) {
e.preventDefault();
var invalidCount = $('select').filter(function() {
return ($(this).val() === '#');
}).addClass('warning').length;
if (invalidCount == 0) {
alert('valid');
}
});
});
Demo: http://jsfiddle.net/TimWolla/QxBH9/
if($("select:selected").val() == '#') {
$("select").addClass("warning");
}
http://api.jquery.com/selected-selector/

Categories