Issue on Checking Multi Inputs Calculation Using each() - javascript

Can you please take a look at this Demo and let me know why I am not able to do the calculation check using the each iterator?
As you can see I tried to use :
if (!parseInt($(this).val()) === ((parseInt($(this).closest('div').find('.upper').text())) - parseInt($(this).closest('div').find('.lower').text()))) {}
Which it didnt work then I used this :
if (!parseInt($(this).val()) === ((parseInt($(this).prev('.upper').text())) - parseInt($(this).prev('.lower').text()))) {
but still not validating the input?

I'm not sure if that what you want to achieve, take a look at following example :
$('#test').on('click', function (e) {
$("input").each(function () {
if ($(this).val().length === 0)
{
$(this).addClass('input-error');
} else {
var upper = parseInt($(this).prev().prev().text());
var lower = parseInt($(this).prev().text());
var current_value = parseInt($(this).val());
if (current_value != (upper-lower)){
$(this).addClass('input-error');
}else{
$(this).removeClass('input-error');
}
}
});
});
.input-error {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper">5</div>
<div class="lower">2</div>
<input type="text" id="txt1">
<hr />
<div class="upper">7</div>
<div class="lower">3</div>
<input type="text" id="txt2">
<hr />
<div class="upper">200</div>
<div class="lower">66</div>
<input type="text" id="txt3">
<hr />
<br />
<button type='button' id="test">Test</button>

Related

How to compare two inputs and show a div

I need to make a simple js. Nothing fancy - just show or hide an element only if the inputs have the same value. All before send the form.
<form>
<input type="number" name="some1" id="some1">
<input type="number" name="some2" id="some2">
<div id="showhide">The inputs are the same</div>
<input type="submit">
</form>
The result can be something like this.
if(#some1(value)==#some2(value)) {
#showhide.show()
} else {
#showhide.hide()
}
Your jquery should be like this:
if($('#some1').val() == $('#some2').val()) {
$('#showhide').show();
} else {
$('#showhide').hide();
}
Something like this?
$("#some1, #some2").on("keyup change", function(){
let firstEl = $("#some1"),
secondEl = $("#some2"),
conditionalEl = $("#showhide");
if (firstEl.val() == secondEl.val() ) {
conditionalEl.show();
} else {
conditionalEl.hide();
}
});
#showhide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" name="some1" id="some1">
<input type="number" name="some2" id="some2">
<div id="showhide">The inputs are the same</div>
<input type="submit">
</form>

create div dynamically by passing css id and class to jquery method

I have div which needs to be repeated(create dynamically) on a button click.i have a working code,but it needs to be used many places across pages so i would like to make it a generic one,like i need to pass only particular div id as an input parameter to that method.
function textbox_add(id){
console.log(id)
var counter = 0;
$('#'+id).on('click','.newField', function () {
console.log(counter);
if(counter >= 3){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
$('#'+id).append(newthing);
counter++;
});
$('#'+id).on('click','.remove', function () {
if (counter == 0)
{
return false
}
$(this).parent().remove();
counter--;
});
}
if i use it outside the method it works perfect.The goal is to create 4 text boxes dynamically and if i remove it should remove one by one.
here is my fiddle
Demo
Issues facing when i place inside method are:
On first click it creates single div on second click it creates two div's then continues for further click's.
On clicking remove it works like create.
when i click new again it creates the total of removed,created(earlier) all the div's.
I am not able to find where am missing.
I am not too sure what you are trying to do with the id (I assume it is your div id) that you are adding but you can try replacing your counter with a count of the elements:
function textbox_add(id){
$('#'+id).on('click','.newField', function () {
if($("#" + id + " > .addNew").length >= 4){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
$('#'+id).append(newthing);
});
$('#'+id).on('click','.remove', function () {
if ($("#" + id + " > .addNew").length == 1)
{
return false
}
$(this).parent().remove();
});
}
textbox_add('test');
working Fiddle
OP basically wants an onclick(html) on the add button, like:
function textbox_add(id) {
if ($("#" + id + " > .addNew").length >= 4) {
alert("Reached Maximum");
return false;
}
var newthing = $('#'+id+' .addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').attr('onclick','').end();
$('#' + id).append(newthing);
$("#" + id + " > .addNew").on('click', '.remove', function () {
if ($("#" + id + " > .addNew").length === 1) {
return false;
}
$(this).parent().remove();
});
}
working codePen
It works fine, fiddle
You need to pass a wrapper id since you're cloning the .addNew content.
Example:
<div class="container" id="test">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
JS
textbox_add('test');
Your code was actually working well when you use id as selector, but worked wrong (adding multiple times new inputs for example) when you were using class as selector (because multiple elements share the same class).
I have edited it so you can use with id and class selectors:
HTML
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
<div id="other_container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
JS
function textbox_add(selector){
console.log(selector);
var max_allowed = 3;
$(selector).on('click','.newField', function () {
console.log($(this).parents(selector).find(".addNew").length);
if($(this).parents(selector).find(".addNew").length > max_allowed){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
console.log($(this).parents(selector));
$(this).parents(selector).append(newthing);
});
$(selector).on('click','.remove', function () {
if (!$(this).parents(selector).find(".addNew").length > 1){
return false
}
$(this).parent().remove();
});
}
textbox_add(".container");
textbox_add("#other_container");
And here is the working JSFiddle.
I think that this is not the correct way to approach the problem, but the OP really wants to do it this way.
HTML
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" onClick="textbox_add(this)" />
<br />
<br />
</div>
</div>
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" onClick="textbox_add(this)"/>
<br />
<br />
</div>
</div>
JS
function textbox_add(element){
var max_allowed = 3;
if($(element).parents(".container").find(".addNew").length > max_allowed){
alert("Reached Maximum");
return false
}
var newthing = $('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').attr('onclick','textbox_remove(this)').unbind('click').end();
$(element).parents(".container").append(newthing);
}
function textbox_remove(element){
if (!$(element).parents(".container").find(".addNew").length > 1){
return false
}
$(element).parent().remove();
}
Working JSFiddle
I think this might be what you are trying to do. The main thing I'm not sure of is what you intend to pass in as the id parameter. But tell me if this fills the bill.
http://jsfiddle.net/abalter/xdsacvdm/12/
html:
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
JavaScript:
$('#createField').on('click', function () {
//alert('new field clicked');
var el = createField('some-id', $('#generator').val());
$('.container').append(el);
});
function createField(id, text) {
var numFields = $('.container').find('.added').length;
if (numFields>3)
{
alert("Maximum reached");
return false;
}
var $outerDiv = $('<div>').addClass('newOne').addClass('added').attr('id', id);
var $textBox = $('<input>').attr({'type': 'text','value': text});
var $button = $('<input>').attr({'type': 'button' , 'value': 'Remove Field!'});
$outerDiv.append($textBox);
$outerDiv.append($button).append('<br/>').append('<br/>');
$button.on('click', function(){
$(this).closest('div').remove();
});
return $outerDiv;
}

Cannot make simple jQuery work

I'm learning jQuery, but I can't make this example work. I know it's quite simple but I don't know what I'm missing. I'm trying to add the class "invalid" in a textfield.
<script src="../jquery/jquery-1.8.2.js"></script>
<script src="../jquery/jquery.ui.effect.js"></script>
<script>
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
return false;
}
});
</script>
<main>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</form>
</main>
There is a syntax error in your Javascript. The corrected Javascript:
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
return false;
}
});
});
Fiddle here: https://jsfiddle.net/s9x1Ldfm/
However I would add the return does not make a lot of sense. It returns false sometimes and void others. What exactly are you trying to do with that?
So, the problem in your code is that you are missing some closing ')' and '}'. The following will make it correct:
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
} // end of for
return false;
} // end of if
}); // end of click
});
You can try to debug your javascript by using the debugger in the browser, by clicking F12. In the Element/Console section, you can see the error messages you have in your code. It will give you some hints regarding the error you have. Also, if you do not have any syntax problem, you are able to use
debugger;
In your code and when you run it in your browser with the debugger mode (F12), you can debug step by step into your code and look at the values of the variables and see how your program is behaving.
But, if in your code you just want to see if the input text is empty or not by the time the user click the button, you can try the following snippet:
<script>
$(function() {
$('#create_task').on('click', function() {
event.preventDefault(); // prevents submission
if ($('.validate').val().length > 0) {
$('.invalid').hide();
} else {
$('.invalid').show();
}// end of if
}); // end of click
});
</script>
<main>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<div class="invalid" style="display:none">Invalid input</div>
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button id="create_task" class="btn" type="submit" name="createTask">Create Task</button>
</form>
</main>
Pay attention how I changed the name of button to id to detect the button without extra validation. I hope it helps.
Use event.preventDefault() to prevent the form submission.
Check out his fiddle.
Here is the snippet.
$('button.btn').click(function(event) {
event.preventDefault();
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
});
.invalid {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate" />
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</form>
Your code has number of issues. First of all, if you want to capture form submission use .submit function and not click on button. Otherwise, you can remove the form tag and capture the click on button element.
Additionally, you can loop through jQuery object using .each. Using for is definitely faster as it is a native JavaScript functionality. I have made a proof of concept on this jsfiddle.
See this code.
$(function () {
$('button.btn').on('click', function () {
if ('create_task' == $(this).val()) {
$('.validate').each(function (i, e) {
if ("" == $(e).val()) {
$('.validate').addClass('invalid');
} else {
$('.validate').removeClass('invalid');
}
})
}
})
});
.invalid
{
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</main>
You have a syntax error as you haven't closed the $(function(){ in your script.
Moreover move your return false to an outer block (so that you'll prevent the default submit behaviour of the button) AND, use submit (which is same as using .submit() method) event as such:
$(function() {
$('button.btn').on('submit', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
return false;
});
});
NOTE: If you wanted, you could change the type='submit' to type='button' while triggering the click event, thus ridding you of returning false in your JavaScript code.

JQuery - filter labels that start with typed in text

i have this list of cities(checkbox and label) and an input field:
<input class="search-filter" type="text"/>
<form autocomplete="off" id="city-search-form" name="city-search-form" action="" method="">
<div id="list" class="multiselect">
<input id="city-id-1" class="css-checkbox" type="checkbox" />
<label for="city-id-1" name="" class="css-label">abc</label>
<input id="city-id-2" class="css-checkbox" type="checkbox" />
<label for="city-id-2" name="" class="css-label">bce</label>
<input id="city-id-3" class="css-checkbox" type="checkbox" />
<label for="city-id-3" name="" class="css-label">cde</label>
<input id="city-id-4" class="css-checkbox" type="checkbox" />
<label for="city-id-4" name="" class="css-label">rgp</label>
</div>
</form>
i am using this jquery code to filter the checkboxes + labels by the words i type in, but the code is not working. How can i filter and show only the labels that start with typed words.
function listFilter(list) {
var input = $('.search-filter');
$(input)
.change( function () {
var filter = input.val();
$('.css-label').filter(function(filter) {
if($('.css-label').text().search(filter) == 0){
.....hide();
}
else {
.......show();
}
});
})
.keyup(function () {
input.change();
.....
}
});
}
$(function () {
listFilter($("#list"));
});
}($));
Try
function listFilter(list, input) {
var $lbs = list.find('.css-label');
function filter(){
var regex = new RegExp('\\b' + this.value);
var $els = $lbs.filter(function(){
return regex.test($(this).text());
});
$lbs.not($els).hide().prev().hide();
$els.show().prev().show();
};
input.keyup(filter).change(filter)
}
jQuery(function($){
listFilter($('#list'), $('.search-filter'))
})
Demo: Fiddle
You can use :contains() selector for filtering:
var input = $('.search-filter');
input.change( function () {
var filter = input.val();
if(filter.length == 0) { // show all if filter is empty
$('.css-label').each(function() {
$(this).show();
$(this).prev().show();
});
return;
}
// hide all labels with checkboxes
$('.css-label').each(function() {
$(this).hide();
$(this).prev().hide();
});
// show only matched
$('.css-label:contains("'+filter+'")').each(function() {
$(this).show();
$(this).prev().show();
});
}).keyup(function() {
$(this).change();
});
jsfiddle
Too late to be accepted as correct but here is an attempt that I was working on before my job got in the way. Thought I may as well post it.
It is case insensitive and supports multiple words (thanks to Arun P Johny for that).
demo
$('.search-filter').keyup(function (e) {
var text = $(this).val();
var $elems = $('.css-label, .css-checkbox');
if (text.length < 1) {
$elems.show();
}
else{
$elems.hide();
var sel = $('label').filter(function () {
return $(this).text().match("\\b", "i" + text)
}).attr('for');
$('#'+sel + ',[for=' + sel + ']').show();
}
});
i have a code below to get the label name
<!DOCTYPE html>
<html>
<head>
<SCRIPT src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</SCRIPT>
<SCRIPT>
$(document).ready(function(){
alert($(".css-label").text());
});
</SCRIPT>
</head>
<body>
<div id="list" class="multiselect">
<input id="city-id-1" class="css-checkbox" type="checkbox" />
<label for="city-id-1" name="" class="css-label">abc</label>
</div>
</body>
</html>
hope this will help you

Jquery select NEXT text field on Enter Key Press

I have made a page using jquery, and on load it selects the first text field automatically. I want it to then move to the next field when the ENTER key is pressed.
$('.barcodeField input').bind('keyup', function(event) {
if(event.keyCode==13){
$("this + input").focus();
}
});
I can't find anything that works on the net. And I've scoured the forums.
I've created a little function which can do what you need. This is the version I use so you may need to change the class names but you should get the idea.
<script type="text/javascript">
$(document).ready(function(){
$(".vertical").keypress(function(event) {
if(event.keyCode == 13) {
textboxes = $("input.vertical");
debugger;
currentBoxNumber = textboxes.index(this);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1]
nextBox.focus();
nextBox.select();
event.preventDefault();
return false
}
}
});
})
</script>
So basically:-
Get all the input fields matching .vertical
Find which is the current text box
Find the next one
Set the focus on that one
You should use:
$(this).next('input').focus();
try this:
(function($){
$.fn.enterNext = function(){
var _i =0;
$('input[type=text], select',this)
.each(function(index){
_i = index;
$(this)
.addClass('tab'+index)
.keydown(function(event){
if(event.keyCode==13){
$('.tab'+(index+1)).focus();
event.preventDefault();
}
});
})
$( "input[type=submit]",this ).addClass('tab'+(_i+1));
}})(jQuery);
for use:
$('form.element').enterNext();
in my case this is the best solution in that I got because the function .next() is strict with elements outside their branch DOM.
The best way is to force an index.
and sorry for my bad English...
Basically, you just need top have the DOM elements in some structure so that you can select the next one. I'd suggest exploiting tabindex, but anything that let's you have a defined order will work.
Here is the solution I came up with. The issue I had was that I needed to maintain tabindex, i.e. it had to function exactly that same as hitting tab. It uses both underscore and jquery.
I've left in my debugging code:
try {
var inputs = $("input[id^=tpVal-]");
var sortedInputs = _.sortBy(inputs, function(element){
var tabIndex = $(element).attr('tabindex');//debugging
var id = $(element).attr('id');//debugging
console.log(id +" | "+ tabIndex +" | "+ $(element));//debugging
return parseInt($(element).attr('tabindex'));
});
$(sortedInputs).each(function (index, element) {
$(element).keyup(function(event){
if(event.keyCode==13) {
var $thisElement = $(element);//debugging
var nextIndex = index+1;//debugging
var $nextElement = $(sortedInputs[nextIndex]);
var thisId = $thisElement.attr('id');//debugging
var nextId = $nextElement.attr('id');//debugging
console.log("Advance from "+thisId+" to "+nextId);//debugging
if($nextElement!=undefined) {
$(sortedInputs[index + 1]).focus();
}
}
});
});
} catch (e) {
console.log(e);
}
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input id="122" class='TabOnEnter' tabindex="1" /><br>
<input id="123" class='TabOnEnter' tabindex="2" /><br>
<input type="text" name="abc" /><br>
<input type="text" name="abc1" /><br>
<input type="text" name="abc2" /><br>
<input type="text" name="abc3" class='TabOnEnter' tabindex="3" /><br>
<input class='TabOnEnter' tabindex="4" /><br>
<input class='TabOnEnter' tabindex="5" /><br>
<input class='TabOnEnter' tabindex="6" /><br>
<!-- <textarea class='TabOnEnter' tabindex="6">Hi, I am a test area</textarea>-->
<input type="submit" value="submit" class='TabOnEnter' tabindex="7">
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).on("keypress", ".TabOnEnter", function (e)
{
//Only do something when the user presses enter
if (e.keyCode == 13)
{
var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
console.log(this, nextElement);
if (nextElement.length)
nextElement.focus()
else
$('[tabindex="1"]').focus();
}
});
//Hidden inputs should get their tabindex fixed, not in scope ;)
//$(function(){ $('input[tabindex="4"]').fadeOut(); })
</script>
</body>
</html>
This code works for me
HTML:
<div class="row">
<div class="col-md-3"> Name </div>
<div class="col-md-3"> <input type="text" /> </div>
</div>
<div class="row">
<div class="col-md-3"> Email</div>
<div class="col-md-3"> <input type="email" /> </div>
</div>
Jquery code:
$(document).on('keypress', 'input,select', function (e) {
if (e.which == 13) {
e.preventDefault();
$(this).parent().parent().next('div').find('input').focus();
}
});

Categories