jQuery Stop duplicate append - javascript

What i'm trying to do here i have 1 select box and one input.
The select box have 3 options with values 1,2 and 3 and the input is in div with id INPUT.
What i want here is when i select the options with value 3 to remove the whole div tag with id INPUT, and then when i click again example on 1 or 2 the DIV tag to append again. But when i'm clicking on 1 or 2 the div tag is appending again and again.
Is there is a chance to check if the div tag exist and not to append.
Here is my jQuery :
$('select').change(function(){
var val = $(this).val();
if(val == '3'){
$('#INPUT').remove();
}
if(val !== '3'){
$('.valuta').before('<div id="INPUT"><input type="text" class="price"></div>');
}
});
Any help will be appreciated.
Thanks.

Yes, it's possible. Change this:
if(val !== '3'){
to this:
if(val != '3' && $("#INPUT").size() == 0){
This way, we're asking if there is already a div with id = INPUT, if there is none, then we add one.
Cheers

Check whether the element with the id INPUT already exists before adding a new one
if (val != '3' && !$('#INPUT').length) {
$('.valuta').before('<div id="INPUT"><input type="text" class="price"></div>');
}
Demo: Fiddle
Also you can fine tune the if condition because if the value is not 3 then you want to have the input field so there is no need for the second if condition just use else block in the first condition
$('select').change(function () {
var val = $(this).val();
if (val == '3') {
$('#INPUT').remove();
} else if (!$('#INPUT').length) {
$('.valuta').before('<div id="INPUT"><input type="text" class="price"></div>');
}
})
Demo: Fiddle

Related

JQuery selecting only the element inside the selected one

I'm currently having problem selecting the right element on a form
Here is my code:
$(document).ready(function(){
$(".wpcf7-submit").click(function () {
if($('.errorName').length > 0){
return false;
}
});
var selectorArray = [$('input[name="name"]'), $('input[name="Company"]')];
$.each(selectorArray, function(){
$(this).on('blur',function(){
if($('.errorName').length == 0 && (($(this).val().length < 4 && $(this).val().length != 0) || /^[a-zA-Z0-9- ]*$/.test($(this).val()) == false))
{
$(this).after('<span class="wpcf7-not-valid-tip errorName" role="alert">Field is not right.</span>');
}
else
{
if($(this).val().length > 3 && /^[a-zA-Z0-9- ]*$/.test($(this).val()) == true)
{
$(this).find('.errorName').remove();
}
}
});
});
});
Basically, I want to check, on unfocus, if what the user has input is good for a couple of fields inside the form, else an error message appears. Unfortunately, I can't seem to remove the error message, and this code stucks that message on the first field the user inputs wrong. After that, it won't come off even if the input typed after the first unfocus satisfies the conditions.
I'm testing on a simple form with 2 text inputs and 1 submit. Without the remove part, I can see both messages being displayed and on
$(this).find('errorName').first().remove();
It's the second element that gets stuck with the error message.
You're placing the errorName span after the input element, so you need to look for a sibling instead. You can use .next() for this.
$(this).next('.errorName').remove();

jQuery problems with function

What i'm trying to do here is if the selection is equal to value 10 the click function to be available only if selection is equal to 10. But when i change to other ex. category with different value the radio click function is still available. ?
I have 6 radio boxes with value 1,2,3,4,5,6 so what i want to do if value == 4 to slidedown another div while i'm in category with value 10.(selection).
How can i fix this problem ? Here is my sample code.
$('#category').on('change', function () {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
if(selection == '10'){
$("input:radio[name='checkbox']").click(function() {
var radio = $(this).val();
if(radio == '4' && selection == '10') {
$('#slidedown'+selection).slideUp();
} else {
$('#slidedown'+selection).slideDown();
}
});
});
Thanks, any help will be appreciated.
EDIT : I want to slideUp the currect div which is slided down by the category value if radio box with value 4 is checked.
You should have another selection var inside the click callback:
$('#category').on('change', function () {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
});
$("input:radio[name='checkbox']").click(function() {
var selection = $('#category').val(); //This does the trick
var radio = $(this).val();
if(radio == '4' && selection == '10') {
$('#slidedown_another').slideUp();
} else {
$('#slidedown_another').slideDown();
}
});
Also, callbacks must be separated for not binding a new listener each time
Hope this helps. Cheers
Use the disabled property to enable and disable the radio buttons.
$('#category').change(function() {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
$('input:radio[name=checkbox]').prop('disabled', selection != '10');
});
$("input:radio[name='checkbox']").click(function() {
var radio = $(this).val();
if(radio == '4') {
$('#slidedown_another').slideUp();
} else {
$('#slidedown_another').slideDown();
}
});
Your code is adding a handler when the select has the correct value, but it never removes the handler when the select changes to a different value. Also, every time they select 10 it was adding another handler, so the handler would then run multiple times.

How to check if the any of my textbox is empty or not in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Check if inputs are empty using jQuery
I have form and textboxes, how will I determine if any of these textboxes is empty using javascript if else statement once a form button is clicked.
function checking() {
var textBox = $('input:text').value;
if (textBox == "") {
$("#error").show('slow');
}
}
Thanks in advance!
By using jQuery selectors for selecting the elements, you have a jQuery object and you should use val() method for getting/setting value of input elements.
Also note that :text selector is deprecated and it would be better to trim the text for removing whitespace characters. you can use $.trim utility function.
function checking() {
var textBox = $.trim( $('input[type=text]').val() )
if (textBox == "") {
$("#error").show('slow');
}
}
If you want to use value property you should first convert the jQuery object to a raw DOM object. You can use [index] or get method.
var textBox = $('input[type=text]')[0].value;
If you have multiple inputs you should loop through them.
function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}
})
alert(empty + ' empty input(s)')
}
You can not use value with jquery object use val() function, But this will check only the first textbox returned by the selector.
Live Demo
function checking() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
}
You can attach blur event and do this validation on losing focus from each textbox.
Live Demo
$('input:text').blur(function() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
});
Validation on submit button click according to discussion with OP
​Live Demo
$('#btnSubmit').click(function() {
$("#error").hide();
$('input:text').each(function(){
if( $(this).val().length == 0)
$("#error").show('slow');
});
});
Try this code:
var textBox = $('input:text').val();
if (textBox==""){
$("#error").show('slow');
}

Javascript loop with dynamic jquery val() not being picked up

I'm trying to pick out the value of an input box using jquery.
No probs there
$('#id_of_my_input_box_1').val();
But I need several so decided to put them into a loop:
============
var config_total_instances = '==some value='
for (var x = 1; x <= config_total_instances; x++) {
if (isset($('#id_of_my_input_box_'+x).val())) {
alert($('#id_of_my_input_box_'+x).val());
}
}
============
If I submit the form and I've got say 10 input boxes, the code above doesn't alert a value if the relevant input box has value.
I'm using a function below to check for values.
============
function isset(my_variable) {
if (my_variable == null || my_variable == '' || my_variable == undefined)
return false;
else
return true;
}
============
Am I missing something vital..? :-(
Addition: I shoudl add that I'm askign why I don't get the value of
$('#id_of_my_input_box_'+x).val()
echoed out in my alert box
Extending #Faber75's answer. You can set a class name for all your text element and then use something like this
$("input:text.clsname").each(function(){
if (isset(this.value)) {
alert(this.value);
}
});
In your current code if you are assigning a string to config_total_instances then it will not work.
don't consider my message an answer, more of a tip.
For a simplier code you could consider adding a class to the textboxes you need to check.
For example adding to all the inputs you need to check the class="sample" you could the use the jquery selector $(".sample") , returning you all the items and then you could simply do
$(".sample").length to count the items and $(".sample")[0].val() (or similar) to get/test values.
Cheers
Have you tried this? (note that there are three =)
if (my_variable === null || my_variable == '' || my_variable === undefined)
As an alternative to this try
if (typeof(my_variable) == 'null' || my_variable == '' || typeof(my_variable) == 'undefined')
Maybe I'm misunderstanding, but can't you just get all the <input>'s in a <form> that aren't :empty if that's the end goal of what you're trying to accomplish?
$('form#some_id input:not(:empty)').each(function () {
// do something with $(this).val() now that you have
// all the non-empty <input> boxes?
});
Or if you're just trying to tell if the user left some <input> blank, something like:
$('form#some_id').submit(function (e) {
if ($(this).find('input[type="radio"]:not(:checked), input[type="text"][value=""], select:not(:selected), textarea:empty').length > 0) {
e.preventDefault(); // stops the form from posting, do whatever else you want
}
});
http://api.jquery.com/category/selectors/form-selectors/

Limit Input text box with Jquery

So I need to have an input box in where people only is allowed to enter either the words "Yes" or "No". No other input is allowed. Does anybody out there knows a plugin or any other easy way to that with Jquery? I found a plugin named constraint (http://plugins.jquery.com/project/constrain), that can prevent the user from typing certain characters, but that is not enough, as the plugin can only prevent the user from typing numbers in an alphabetic field, for example. Drop down boxes or other components are not an option.
Thank you for your help.
Why not something like this (link to jsFiddle)? This will only let you type those characters that are contained in an array of allowed values? I suspect there's a better way to check for the existence of values or partial values in the array instead of looping. But this will be triggered by a user's key press, not when the control loses focus...so the UX may be better.
Hope this helps!!
HTML
Enter text: <input type="text" id="data" />
JavaScript Code
var allowedValues = ['yes','no'];
$(document).ready(function() {
$("#data").keyup(function(e) {
var typedValue = $(this).val(),
valLength = typedValue.length;
for(i=0;i<allowedValues.length;i++) {
if(typedValue.toLowerCase()===allowedValues[i].substr(0,valLength)) {
return;
}
}
$("#data").empty().val(typedValue.substr(0, valLength-1));
});
});
Based on clarification in comment, try this:
Try it out: http://jsfiddle.net/fsPgJ/2/
EDIT: Added a keypress event to deal with the user holding down a key.
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
})
.keypress(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no")
this.value = '';
})
.keyup(function() {
var val = this.value.toLowerCase();
if("yes".indexOf(val) != 0 &&
"no".indexOf(val) != 0) {
this.value = this.value.substr(0,this.value.length - 1);
}
});
Original:
If there's some reason you're not using a <select> or :radio or something, then you could have jQuery check the value on a .blur() event.
Try it out: http://jsfiddle.net/fsPgJ/
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
});
This just clears the input if the (case insensitive) value is not "yes" or "no". I also added an alert() to give the user a little feedback as to why the field was cleared. You may want a different feedback approach.

Categories

Resources