I have a cart options that has a increment the product option . The option has an text input and plus / minus options
Markup
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
there is about 5 to 6 types of input like above
And the JavaScript code:
var minus = $(".quantity-mius");
var plus = $(".quantity-plus");
var itemValue = $(".cart-main-product-qty");
$(".cart-item-qty").each(function(index) {
$(this).find(plus).on('click', function(e){
e.preventDefault();
increment();
});
$(this).find(minus).on('click', function(e){
e.preventDefault();
decrement();
});
});
function increment(){
newValue = itemValue.val();
newValue++;
itemValue.val(newValue);
};
function decrement(){
newValue = itemValue.val();
newValue--;
if(newValue < 1){
itemValue.val(0);
}else{
itemValue.val(newValue);
}
};
When i press the plus button the input value increases in all the inputs and when minus then all decreases.
Onclicking on those icon simply call the function and find its sibling with that class and calculate the value. Try with -
$(".quantity-plus").on('click', function(e){
e.preventDefault();
increment($(this));
});
$(".quantity-mius").on('click', function(e){
e.preventDefault();
decrement($(this));
});
function increment($this){
itemValue = $this.siblings('.cart-main-product-qty');
newValue = itemValue.val();
newValue++;
itemValue.val(newValue);
};
function decrement(){
itemValue = $this.siblings('.cart-main-product-qty');
newValue = itemValue.val();
newValue--;
if(newValue < 1){
itemValue.val(0);
}else{
itemValue.val(newValue);
}
};
Why don't you try like this
$(".quantity-plus").on('click', function(e){
e.preventDefault();
increment();
});
$(".quantity-mius").on('click', function(e){
e.preventDefault();
decrement();
});
It will work
In increment and decrement, you're selecting all the input elements at once (the selection is happening outside of the each call at the top of the script).
You are therefore trying to call val() and val(n) on the entire collection of inputs, in affect trying to increment and decrement all of them at once, except in reality val() (with no arguments) doesn't work like that (it should never be used with a collection on inputs, but instead with only one input at a time).
You should select the input using find within the each like you do with the + and - buttons, and pass the found input to increment and decrement as parameters to those functions, or you should do the increment or decrements inline in the each block itself instead of in separate functions.
this works : manage click event before selecting each input
<script type="text/javascript">
var itemValue = $(".cart-main-product-qty");
$( ".quantity-mius" ).click(function(e) {
e.preventDefault();
$( ".cart-main-product-qty" ).each(function( index, element ) {
console.log('decrement');
decrement();
})
});
$( ".quantity-plus" ).click(function(e) {
e.preventDefault();
$( ".cart-main-product-qty" ).each(function( index, element ) {
console.log('increment');
increment();
})
});
function increment(){
newValue = itemValue.val();
newValue++;
itemValue.val(newValue);
};
function decrement(){
newValue = itemValue.val();
newValue--;
if(newValue < 1){
itemValue.val(0);
}else{
itemValue.val(newValue);
}
};
</script>
You have to target only the input element related to clicked plus/minus button so
$(".cart-item-qty .quantity-mius").click(function(index) {
$(this).closest('td').find('.cart-main-product-qty').val(function(i, val) {
var value = +val || 0;
return value > 1 ? value - 1 : 0
})
});
$(".cart-item-qty .quantity-plus").click(function(index) {
$(this).closest('td').find('.cart-main-product-qty').val(function(i, val) {
return +val + 1 || 1;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
</table>
This works:
$(document).ready(function(){
var minus = $(".quantity-mius");
var plus = $(".quantity-plus");
$(plus).on('click', function(e){
e.preventDefault();
$(this).parent().find("input.cart-main-product-qty").val(parseInt($(this).parent().find("input.cart-main-product-qty").val())+1);
});
$(minus).on('click', function(e){
e.preventDefault();
$(this).parent().find("input.cart-main-product-qty").val(parseInt($(this).parent().find("input.cart-main-product-qty").val())-1);
});
});
FIDDLE
You said you had more that one of these on the page. Is that because there are multiple items in the cart? I added a data- attribute to your container element. Just a thought. It may help differentiate them.
<td class="cart-item-qty" data-cartItemId="3">
<div class="quantity-minus">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" />
</div>
<div class="quantity-plus">+</div>
</td>
You are casting too wide a net in your increment and decrement functions. You need to find itemValue that same way you are finding plus and minus within $(this) in your foreach. You need to pass along a single element.
If you check the docs on jQuery, there is a prescribed way to pass variables to the eventhandler that is called by on. jQuery API docs
Try this:
var minus = $(".quantity-minus");
var plus = $(".quantity-plus");
var itemValue = $(".cart-main-product-qty");
$(".cart-item-qty").each(function(index) {
// need to use THIS this in a nested context.
var that = $(this);
$(this).find(plus).on('click', { target: that.find(itemValue) }, increment);
$(this).find(minus).on('click', { target: that.find(itemValue) }, decrement);
});
function increment(event) {
event.preventDefault();
var el = event.data.target;
newValue = el.val();
newValue++;
el.val(newValue);
};
function decrement(event) {
event.preventDefault();
var el = event.data.target;
newValue = el.val();
newValue--;
if(newValue < 1){
el.val(0);
}else{
el.val(newValue);
}
};
Hope this helps!
Your code looks almost right.
First change this code
var minus = ".quantity-mius";
var plus = ".quantity-plus";
var itemValue = ".cart-main-product-qty";
as you use find you don't need the object.
Then the html is not complete, I used this code to make it working
<table>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1">
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
<tr>
<td class="cart-item-qty">
<div class="quantity-mius">-</div>
<div class="quantity">
<input type="text" class="cart-main-product-qty" value="1" >
</div>
<div class="quantity-plus">+</div>
</td>
</tr>
</table>
While the js is
var minus = ".quantity-mius";
var plus = ".quantity-plus";
var itemValue = ".cart-main-product-qty";
$(".cart-item-qty").each(function(index) {
var outer = $(this)
$(this).find(plus).on('click', function(e){
e.preventDefault();
increment(outer.find(itemValue));
});
$(this).find(minus).on('click', function(e){
e.preventDefault();
decrement(outer.find(itemValue));
});
});
function increment(item){
newValue = item.val();
newValue++;
item.val(newValue);
};
function decrement(item){
newValue = item.val();
newValue--;
if(newValue < 1){
item.val(0);
}else{
item.val(newValue);
}
};
Note that I added an argument to the functions increment and decrement because I guess you want to change just the relative input field
Related
I have the following problem:
I would like to change the value of an input field, which is next to an another element, which will be clicked.
HTML:
<div>
<a id="{$sArticle.articleID}" class="minus"><i class="icon-minus-wide"></i></a>
<input class="quantityNum--input quantity{$sArticle.articleID}" name="sQuantity"
type="text" value="{$sArticle.minpurchase}">
<a id="{$sArticle.articleID}" class="plus"><i class="icon-plus-wide"></i></a>
</div>
JS:
$(document).on('click', ".plus", function (event) {
let currentTarget = event.currentTarget;
let idOfClickedElement = $(currentTarget).attr('id');
let currentQuantity = Number($('.quantity' + idOfClickedElement).val());
$(this).parent().find(".quantity" + idOfClickedElement).val(currentQuantity + 1)
});
There are other input fields which are the same like in the example. Those value changes also, but I want only one.
As each input with +/- is inside a div wrapper, you can use
$(this).closest("div").find(".quantityNum--input")
to get the related input.
There's no need for the numeric IDs when using relative DOM traversal.
Combining the + and - into a single event gives:
$(document).on('click', ".minus,.plus", function() {
var delta = $(this).is(".plus") ? 1 : -1;
$(this).closest("div").find(".quantityNum--input").val((i, val) => {
console.log(val);
return (val * 1) + delta;
});
});
.minus,
.plus {
cursor: pointer
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<a class="minus">[-]<i class="icon-minus-wide"></i></a>
<input class="quantityNum--input" name="sQuantity" type="text" value="100">
<a class="plus">[+]<i class="icon-plus-wide"></i></a>
</div>
<div>
<a class="minus">[-]<i class="icon-minus-wide"></i></a>
<input class="quantityNum--input" name="sQuantity" type="text" value="500">
<a class="plus">[+]<i class="icon-plus-wide"></i></a>
</div>
I thik you are looking for .next and .prev.
note: I like sharing information usingdata-attributes so I've used that. you can use anything else id/class to differentiate. that's upto you
Just created a demo script for you
$('.number-action-button').on('click', function(){
const direction = $(this).data('direction');
if(direction === 'decrement'){
const $input = $(this).next('input[type="number"]');
$input.val($input.val() - 1);
}
if(direction === 'increment'){
const $input = $(this).prev('input[type="number"]');
$input.val(parseInt($input.val()) + 1);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="number-action-button" data-direction="decrement">-</button>
<input type="number" value="0" />
<button class="number-action-button" data-direction="increment" >+</button>
simple solution: bundle the 3 elemts into 1 container, so your parent selector can easily catch the input, the way you already do it.
<div>
<a id="{$sArticle.articleID}" class="minus"><i class="icon-minus-wide"></i></a>
<input class="quantityNum--input quantity{$sArticle.articleID}" name="sQuantity"
type="text" value="{$sArticle.minpurchase}">
<a id="{$sArticle.articleID}" class="plus"><i class="icon-plus-wide"></i></a>
</div>
if you cant(or dont want) change the html use $(this).next() (or $(this).prev() for the plus button) in order to fint the input.
btw: maybe you'll try that funktion (havn't tested it, but at least it should give you an idea how to)
$(document).on('click', ".plus,.minus", function (event) {
let input_quantity=false;
if($(this).hasClass('plus'){
input_quantity=$(this).prev();
input_quantity.val(parseInt(input_quantity.val())+1);
}else{
input_quantity=$(this).next();
input_quantity.val(parseInt(input_quantity.val())-1);
}
});
Here I need to get all the values entered in the input field. But it echoes only the first value.
ie. When I press the + and give some values, I need to get that value too.
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('#package').change(function() {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
alert(arr);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add"></div>
</div>
$('.package').change(function() {
You are using an ID in your input type="text". IDs are only used once. If you want to add the listener to all of your textfields use classes.
In addition to that the .change(function() is only once called, when the dom is ready. That will be a problem too. So the change listener is not added to the generated textfields. Maybe you use something like...
$('.package').on('change', 'input', function() {
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add">
</div>
</div>
<script type="text/javascript">
var addInput = function(e) {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
});
alert(arr);
};
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input class="packageclass" type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
$('.packageclass').unbind().bind('change', addInput);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('.packageclass').unbind().bind('change', addInput);
</script>
Just using loop you can get the particular value from loop.
for (var i = arr.length - 1; i >= 0; i--) {
arr[i];
//work with arr[]
}
I have used event delegation to capture the events and take appropriate action.
In this, you can add a event listener to your parent element i.e., click to the .body in my case. When I click on the .add button, the event propagates and .body click handler gets invoked. By checking for event.target we can find out the origin of event and add or remove the divs.
Similary we can listen for the change event of the input boxes and take appropriate actions.
$('#body').click(function(e) {
if(e.target.className === 'add') {
$('#body').append(`
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
<button class="remove">-</button>
</div>
`);
}
if(e.target.className === 'remove') {
$(e.target).parent().empty();
}
});
$('#body').change(function(e) {
console.log(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="body">
<h6>Sales Package </h6>
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
</div>
</div>
Just add class="packageclass" to the input when creating your clone variable.
https://jsfiddle.net/289xvmu7/
var clone = '<div class="add1"><input type="text" name="selprice" class="packageclass"/> <input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
I had created Ul which add the student input field with value and user can remove the field as well,Initially I am comparing student field value with each input field which are created to avoid duplication but it works only for first input field value not for others I used loop as well but its not working and not able to remove one input field at a time.
Here is my fiddle code
$('#addBtn').click(function () {
var studentArray = $(".students").text();
var i=" " ;
console.log(studentArray);
var studentSplitResult = studentArray.split('Remove');
console.log(studentSplitResult);
for (var i = 0; i < studentSplitResult.length; i++) {
if ($("#selectStd").val() !== $(".students").val()) {
$(".stdList").show();
var input_value = $('#selectStd').val();
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
console.log($(".students").val());
// console.log(studentSplitResult[i]);
};
return false;
}
});
//prevent default action
$(document).on('click', 'a', function (e) {
e.preventDefault();
$(this).parent().remove();
});
You can simplify your code like below.
Just check any text input has the new value before adding using filter. It will also handle case insensitivity (remove if required).
Also while removing consider the removing the text input only.
Added e.preventDefault() to restrict the form posting. change or remove it as per requirement.
$('#addBtn').click(function(e) {
e.preventDefault();
var input_value = $("#selectStd").val();
var isValid = $('input.students').filter(function() {
return this.value.toLowerCase() == input_value.toLowerCase();
}).length <= 0;
if (isValid) {
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
} else {
alert('Duplicate');
}
});
//prevent default action
$(document).on('click', 'a.deleteStd', function(e) {
e.preventDefault();
$(this).prev('.students').remove();
$(this).remove();
});
<body>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td><input class="form-control" id="selectStd" placeholder="Please select students"></td>
<td><button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button></td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label><br>
<br>
</ul>
<table>
</table>
</form>
</div>
</div>
</div>
</body>
I have encountered two issues: input validation itself (your question) and the removal of the element when you click on the anchor element.
For input validation, I have rewritten it a bit. What I did is
1. Obtain new student value
2. Check if not empty by if(newStudent). If it's empty, nothing happens
3. obtain other inputs
4. match the new input against the values inside other inputs
4a. if match, don't add it.
4b. if no match, add it
For removing the element, You need to revise your HTML. It's not so correct. I have wrapped it around with a <section> element to have a save removal and corrected the HTML use.
A side note, you may also reconsider this
$(document).on('click', 'a', function(e) {
e.preventDefault();
$(this).parent().remove();
});
If your HTML page has multiple anchor (<a>) elements, this function is used too on another anchor elements. If you click on these, it will remove these from the page upon click. If you don't want it, please revise the above function.
$('#addBtn').click(function(e) {
// obtain new student value
var newStudent = $('#selectStd').val();
// check if it is not empty
if (newStudent) {
// obtain other names and check if there is no match
var studentArray = $(".students");
var hasMatch = false;
studentArray.each(function(i, el) {
if (el.value === newStudent) {
hasMatch = true;
return; // stopping loop
}
});
// if there is no match, add student
if (!hasMatch) {
$('ul.stdList').append('<section><input class="students" value="' + newStudent + '" />Remove</section>');
}
}
return false;
});
//prevent default action
$(document).on('click', 'a', function(e) {
e.preventDefault();
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td>
<input class="form-control" id="selectStd" placeholder="Please select students">
</td>
<td>
<button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button>
</td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label>
<br>
<br>
</ul>
</form>
</div>
</div>
When adding you try this:
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
Unfortunately this will not result in what you expect. The anchor will be adding by your browser next to the input not nested. Like this:
<input class="students" value="thevalue" />
<a href class="deleteStd">Remove</a>
So if you do this afterwards for removing $(this).parent().remove(); you will remove the entire container.
What you need to do is this:
$('ul').append('<div><input class="students" value="' + input_value + '" />Remove</div>');
This will work. I have updated your fiddle: https://jsfiddle.net/Lojdfyhn/1/
So based on your requirements, try this below code:
Student names can't be duplicate
And on removing, all names shouldn't removed.
While adding, code checks if the student name exists. If yes, it throws an error/alert.
$('#addBtn').click(function() {
var valueToCheck = $("#selectStd").val();
var flag = true;
$(".students").each(function() {
if ($(this).val() === valueToCheck) {
flag = false;
}
});
if (flag) {
$('ul').append('<span class="addedStudent"><input class="students" value="' + valueToCheck + '" />Remove</span>');
} else {
alert(valueToCheck + " already exists.");
}
return false;
});
//prevent default action
$(document).on('click', 'a.deleteStd', function(e) {
e.preventDefault();
$(this).parents(".addedStudent:first").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td><input class="form-control" id="selectStd" placeholder="Please select students"></td>
<td><button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button></td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label><br>
<br>
</ul>
<table>
</table>
</form>
</div>
</div>
You are trying to delete the parent element of anchor tag.
Just update your code like this
$('ul').append('<div><input class="students" value="' + input_value + '">Remove</input></div>');
then clicking on anchor will delete the parent of anchor element.
Hello first of all you need to get a good understanding of the DOM traversing, which can really help you to organise the students that you are adding to the list, and removing.
Here a simple solution can be implemented as follows.
First encapsulate all the students in a div tag with 'students' class name, and in that div, place the student text field with 'stdname' class and the anchor tag to help in removing the student details.
Now when traverse through all the students with 'stdname' class and check if there is a duplicate value.
Here is the code please check out.
and check on jsfiddle too.http://jsfiddle.net/naveen_namani/842bf5ke/1/
$('#addBtn').click(function () {
var student_list=document.querySelectorAll(".students .stdname");
var selectStd=document.getElementById("selectStd");
var duplicate=false;
for(var i=0;i<student_list.length;i++) {
if(student_list[i].value==selectStd.value) duplicate=true;
}
if(duplicate==false) {
$('ul').append('<div class="students"><input value="'+selectStd.value+'" class="stdname"/>Remove');
}
return false;
});
$(document).on('click', 'a', function (e) {
e.preventDefault();
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style="width:422px;border:1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType" >
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td>
<input class="form-control" id="selectStd" placeholder="Please select students">
</td>
<td>
<button id="addBtn" class="btn btn-default" style="margin-left: 17px;" >Add</button>
</td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label>
<br><br>
</ul>
<table ></table>
</form>
</div>
</div>
Essentially, I am trying to have my form clear all input fields on submit if the default values are still present. Then if there are default values still present, then the submit process is stopped. The form clears the fields on submit, but wont stop the submit button from executing like its suppose to. Please help me out on this. I wrote this myself, and still trying to figure out why it isn't working.
The jQuery Script Below:
<script type="text/javascript" >
$(document).ready(function(){
$(".forms").each(function(){
var DefaultValue = $(this).value;
$("#Form_1").submit(function(){
if ( CheckInput() == "empty" ){
return false;
}
});
function CheckInput(){
var x = '';
$(".forms").each(function(){
if ($(this).value == DefaultValue){
this.value = '';
var y = "empty";
return y;
}
x = y;
return x;
});
}
});
});
</script>
The HTML code below:
<form id="Form_1">
<table>
<tr>
<td>
<table cellpadding="2" cellspacing="3" width="500px">
<tr>
<td>
<div class="InputContainer">
<input name="FirstName" value="First Name" class="forms" type="text"required="true" ></input>
<div class="InfoBlurp">First Name<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="BirthDate" value="Birth Date(MM/DD/YYYY)" class="forms" type="text" required="true" ></input>
<div class="InfoBlurp">Birth Date(MM/DD/YYYY)<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="Email" value="Email#sample.com" validType="email" class="forms" type="text" required="true"/></input>
<div class="InfoBlurp">Email#sample.com<div class="InfoTip"></div></div></div>
</td>
</tr>
</table>
<input id="Button_1" class="topopup" type="submit" value="" style="background-color: #FFFFFF; border:none; cursor:pointer;">
</form>
Your checkInput method is not returning anything, you are returning values from the each callback function not from the CheckInput method.
$(document).ready(function () {
$(".forms").each(function () {
var DefaultValue = $(this).value;
$("#Form_1").submit(function () {
if (CheckInput() == "empty") {
return false;
}
});
function CheckInput() {
var x = '';
$(".forms").each(function () {
if ($(this).value == DefaultValue) {
this.value = '';
x = "empty";
//return false to stop further iteration of the loop
return false;
}
});
return x;
}
});
});
I have a checkboxlist control, in this control I wan't every checkbox to fire an event whenever the checkbox is clicked (manually or programmatically).
Html code generated by checkboxlist lloks something like below:
<div id="divleft">
<table id="MainContent_CheckBoxList1">
<tbody>
<tr>
<td><input id="MainContent_CheckBoxList1_0" name="ctl00$MainContent$CheckBoxList1$0" onclick="router(this);" value="1" type="checkbox"><label for="MainContent_CheckBoxList1_0">Option1</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_1" name="ctl00$MainContent$CheckBoxList1$1" onclick="router(this);" value="2" type="checkbox"><label for="MainContent_CheckBoxList1_1">Option2</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_2" name="ctl00$MainContent$CheckBoxList1$2" onclick="router(this);" value="3" type="checkbox"><label for="MainContent_CheckBoxList1_2">Option3</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_3" name="ctl00$MainContent$CheckBoxList1$3" onclick="router(this);" value="4" type="checkbox"><label for="MainContent_CheckBoxList1_3">Option4</label></td>
</tr>
</tbody>
</table>
</div>
On click of checkbox I am hiding or showing div(s). The div looks like:
<div id="divright">
<div id="divoption1" style="display: none;">
I am in option1 div
</div>
<div id="divoption2" style="display: none;">
I am in option2 div
</div>
<div id="divoption3" style="display: none;">
I am in option3 div
</div>
</div>
</div>
I have a jquery code which does the heavy duty work for showing / hiding divs.
$(document).ready(function () {
RunOnce();
});
function uncheckAllCheckboxes(previouscheckedCheckboxValue, currentcheckedCheckboxValue) {
if (previouscheckedCheckboxValue != null && previouscheckedCheckboxValue != currentcheckedCheckboxValue) {
window.isRunOnce = 'false';
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false).click();
//variable used to avoid infinite loop
window.isRunOnce = null;
}
return currentcheckedCheckboxValue;
}
function router(control) {
if (control.value == '1') {
Option1Controller(control.value);
}
if (control.value == '2') {
Option2Controller(control.value);
}
if (control.value == '3') {
Option3Controller(control.value);
}
}
function Option1Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption1]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption1]').hide();
}
}
function Option2Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption2]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption2]').hide();
}
}
function Option3Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption3]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption3]').hide();
}
}
function RunOnce() {
Option1Controller('1');
Option2Controller('2');
Option3Controller('3');
}
Problem lies with function uncheckAllCheckboxes, in this function, I am unchecking previously checked checkboxes:
I have tried:
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false);
Above query unchecks the corresponding checkbox but does not fire the onclick event?
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').click(); just after the above query.
It fires the click event but also undoes 1, so it is useless.
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false).click();
This query also seems to do nothing
My requirement is simple: I need to pro grammatically check/uncheck checkboxes which are identified by parent id and the value of checkbox control. After checking/unchecking, the control should fire click event also.
Any help shall be appriciated.
Note: I am new to this jquery stuff, so any improvements in my code are also welcomed.
Have you considered using radio buttons instead of checkboxes? They have same behavior you trying to achieve with checkboxes. I've created a fiddle
HTML
<label for="checkbox1">Div 1</label>
<input type="checkbox" name="div" id="checkbox1" data-div-id="1">
<label for="checkbox2">Div 2</label>
<input type="checkbox" name="div" id="checkbox2" data-div-id="2">
<label for="checkbox3">Div 3</label>
<input type="checkbox" name="div" id="checkbox3" data-div-id="3">
<hr/>
<div id="div1">DIV1</div>
<div id="div2">DIV2</div>
<div id="div3">DIV3</div>
<br/>
<label for="radio1">Div 4</label>
<input type="radio" name="div" id="radio1" data-div-id="4">
<label for="radio2">Div 5</label>
<input type="radio" name="div" id="radio2" data-div-id="5">
<label for="radio3">Div 6</label>
<input type="radio" name="div" id="radio3" data-div-id="6">
<hr/>
<div id="div4">DIV4</div>
<div id="div5">DIV5</div>
<div id="div6">DIV6</div>
JS
$(document).ready(function() {
var checkboxes = $('input:checkbox'),
radios = $('input:radio'),
divs = $('div');
// hide all divs
divs.hide();
checkboxes.change(function( e ) {
var e = e || window.event,
target = e.target || e.srcElement;
$('#div' + $(target).data('div-id')).toggle();
});
radios.change(function( e ) {
var e = e || window.event,
target = e.target || e.srcElement;
divs.hide();
$('#div' + $(target).data('div-id')).toggle();
});
});
you can see the comparison between both. And wouldn't use inline js anymore and css when possible. And try to avoid using tables if it not for tabular data, they are known for causing performance issues. Read this
I think you are using too much code.
Check this:
$('input[type="checkbox"]').change(function () {
var this_index = $(this).closest('tr').index(); //check the index of the tr of this input
$("#divright > div").eq(this_index).show(); //show the div inside divright that has same index as this_index
});
And this demo. I removed all inline function calls. I think this is a easier way.