So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).
Here is my code:
var ingrCount = 0
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);
var ingrClose = $("<button>");
ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");
// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);
// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);
// Clear the textbox when done
$("#ingredients").val("");
// Add to the ingredient list
ingrCount++;
if (ingredientInput === "") {
}
});
So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.
If you're testing if ingredientInput is empty, can you just return from within the click event?
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if(ingredientInput === '') { return; }
// rest of code
Simply use :
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if (ingredientInput.length == 0) {
return false;
}
// ..... your code
Related
var container = document.createElement("lastExp");
container.innerHTML = 'html code new form field';
document.getElementById("lastExp").appendChild(container);
It's simple i click button extra form field is added.
Question: When i refresh page how to not lose this extra fields on my form.
Stack Overflow is not the place to write code, but this will sits here in case someone besides OP need.
It's a minimal example--getting started--with localStorage. As I mentioned, under the hood, you have to append that element every time the page is loaded.
The snippet won't work here, unfortunately because the iframe is sandbox'd. Head over to my hub to experiment it.
var container = document.getElementById('container'),
toggle = document.getElementById('toggle');
element = null;
// initial check
init();
// add click event and listen for clicks
toggle.onclick = function() {
// both cases will update localStoage _inputIsThere
// if element is null -- doesn't exists, then add it
if (element == null) {
add();
} else {
// remove the element
remove();
}
}
// check if key exists in localStorage; this is where all the "magic" happens.
function init() {
var exists = localStorage.getItem('_inputIsThere');
if (exists && exists == 'true') {
add();
}
}
function remove() {
element.remove();
element = null;
// update key in localStorage to false
localStorage.setItem('_inputIsThere', false);
}
// adds the input and updates
function add() {
var e = document.createElement('input');
e.type = 'text';
element = e;
container.appendChild(e);
// update key in localStorage to true
localStorage.setItem('_inputIsThere', true);
}
<button id="toggle">Add/Remove</button>
<div id="container"></div>
I ve got numérous checkboxes in my page, each time I click a checkbox, I get the id im interested in and I fill a hidden form. My script is working but if I unclick the checkbox, it should delete the id from the hidden field (right now it appends again the id in the hidden field). How can I writte such a script ? Here's my code so far:
$(document).ready(function() {
var string = "";
$('.checkbox').on('change', function() {
var subscription_id = $(this).parent().attr('id');
if(string == "") {
string = subscription_id;
} else {
string = string + ", " + subscription_id;
}
$('#select_players').val(string);
$('#subscription_ids_export').val(string);
})
})
You can simplify this by retrieving only the subscription_id values from checkboxes which are checked instead of adding/removing values each time.
Try this:
$('.checkbox').on('change', function() {
var subscriptionIds = $('.checkbox:checked').map(function() {
return $(this).parent().prop('id');
}).get().join(',');
$('#select_players').val(subscriptionIds);
$('#subscription_ids_export').val(subscriptionIds);
})
Example fiddle
I have a db search form with multiple fields. Two of them, job_id and job_desc, I want to be disabled when the other one is used and vice versa. I have written a small Javascript function to do this.
Here is my form code:
<input type="text" id="job_id" oninput="input('job_id','job_desc')" onblur="blur('job_id','job_desc')">
<textarea id="job_desc" oninput="input('job_desc','job_id')" onblur="blur('job_desc','job_id')"></textarea>
Here is my Javascript code:
function input(a,b)
{
var a = document.getElementById(a);
var b = document.getElementById(b);
alert("This will disable "+b); // Let the user know we are disabling the other field
b.value = ""; // Empty the other field
b.disabled = true; // Disable the other field
}
function blur(a,b)
{
var a = document.getElementById(a);
var b = document.getElementById(b);
if(a.value = "") // If the field is empty...
{
b.disabled = false; // Enable the other field.
}
}
I have these problems:
1) For some reason my second field does not re-enable once the first field is empty and blurred. This leads me to believe the onblur() event is not working.
2) Once I type in some text, I get the alert once and it's all good. However, when I empty the field and the re-input some text, the alert doesn't trigger a second time. How do I reset the oninput() event?
Here is my fiddle: fiddle
You can use the "onkeyup" event instead of the other events:
The HTML Code would be :
<input id="job_id" onkeyup="input('job_id','job_desc')">
<br>
<textarea id="job_desc" onkeyup="input('job_desc','job_id')"></textarea>
And the JS funciton :
function input(a, b) {
var ea = document.getElementById(a); // We put A in a variable
var eb = document.getElementById(b); // We put B in a variable
if(ea.value != ""){ // If the element have a value / text in it
if(!eb.disabled) // we check if the other element is disabled, if not, we trigger the alert
alert("This will disable " + b); // Let the user know we are disabling the other field
eb.value = ""; // Empty the other field
eb.disabled = true; // Disable the other field
}else{ // if the element's value is empty (which means that we have erased the existing value)
alert(b + " is now enabled"); // Let the user know we are enabling the other field
eb.disabled = false; // We re-enable the field
}
}
It will work fine on all the browsers..
I hope it will help you !
Besides the solution provided, the reason your code did not work is it was conflicting with a native blur() function on the window object, and so your blur call was calling that instead of your own blur function. You need to change its name.
Another issue once you fix that is in
if(a.value = "") // If the field is empty...
it should have two = signs for comparison.
if(a.value == "") // If the field is empty...
Demo at http://jsfiddle.net/q11m3ahz/6/
I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY
I have a drop down box as shown :
When I change the subject, the alert box shown below appears:
Code :
$("#createquiz_subject").bind("change", (function() {
if(quiz.length !== 0){
var r = confirm("The questions selected will be cleared");
if (r === true) {
$("#leftValues").empty();
} else {
}
}
}));
If I click on OK, then the topic and lesson changes. The same happens when I click on cancel.
When the user clicks on cancel, I want the subject to remain the same which was present before changing it.
How do I carry out this functionality.
You can work around this by first remembering the currently selected section and then manually reverting to it.
var subject = $('#creatquiz_subject');
var currentSubj = subject.val();
subject.bind("change", (function() {
if (!quiz.length) { return; } // Better to just short-circuit here?
if (confirm("The questions selected will be cleared")) {
$("#leftValues").empty();
currentSubj = subject.val(); // Update the current subject var
} else {
subject.val(currentSubj); // Reset to current subject
}
}));
Only one way . Pseudocode is :
<script>
var lastvalue = null;
</script>
<select .... onmousedown="lastvalue = this.index">
....
</select>
oncancel
select.index = lastvalue
tweak the code as per your implementation and jquery used(if used)