How to reset the oninput() html event after first use? - javascript

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/

Related

Having Button not run Function With Empty Input Field

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

I can't stop the alert method in Chrome

I have an input text and a button for checking the input text value.
When the web page is loaded, the input text has the focus and this value is empty by default.
So when you put the focus outside the input text (onblur), the check_input_value(event) function executes the alert("Your input value must not empty") one time when the input text value is empty.
This works perfectly in Firefox. But in Chrome, this alert is executed indefinitely instead of one time.
Here the code (you can try it (try it with Chrome) at https://jsfiddle.net/fcg86gyb/ ) :
<input type="text" id="input_text"> <input type="button" value="Check input value" onclick="check_input_value(event);">
<script type="text/javascript">
//Get the input text element :
input_text = document.getElementById("input_text");
//Put focus in input text :
input_text.focus();
/*Add event listener in the input text element.
On blur, if your input value is empty, then execute check_input_value(event) function
to check input text value :
*/
input_text.addEventListener('blur',
function(event)
{
var event = window.event || event;
check_input_value(event);
}
, false
);
//Function for checking input text value :
//if the input value is empty, display alert "Your input value must not empty", and put focus in input text.
function check_input_value(event)
{
var event = window.event || event;
if(input_text.value == "")
{
alert("Your input value must not empty");
input_text.focus();
return false;
}
}
</script>
So how to execute one time the alert instead of indefinitely in Chrome?
The chrome execute indefinitely instead of one time because your function always return the focus to the input text and always you change the focus your function will be call. In Firefox works well because the input text does not receive the focus in the end of the javascript function.
If you remove input_text.focus(); it is going to work.
Thanks for the link to jsfiddle. I tried working on it and found that the input_text.focus() was getting called recursively.
I commented that and it worked. I think you should call the input_text.focus() somewhere outside where the call may not be recursive.
This is the link where I tried: https://jsfiddle.net/fcg86gyb/1/
//Get the input text element :
input_text = document.getElementById("input_text");
//Put focus in input text :
input_text.focus();
/*Add event listener in the input text element.
On blur, if your input value is empty, then execute check_input_value(event) function :
*/
input_text.addEventListener('blur',
function(event)
{
var event = window.event || event;
check_input_value(event);
}
, false
);
//Function for checking input text value :
//if the input value is empty, display alert "Your input value must not empty", and put focus in input text.
function check_input_value(event)
{
var event = window.event || event;
if(input_text.value == "")
{
alert("Your input value must not empty");
//input_text.focus();
return false;
}
}
If you need to maintain the focus on the textbox after showing the alert box only once, you can make use of temporary variable as I stated in the comment and you can achieve the same as follows:
//Get the input text element :
input_text = document.getElementById("input_text");
//Put focus in input text :
input_text.focus();
var temp = 0;
/*Add event listener in the input text element.
On blur, if your input value is empty, then execute check_input_value(event) function :
*/
input_text.addEventListener('blur',
function(event)
{
var event = window.event || event;
if(temp == 0)
{
check_input_value(event);
}
else
{
button_focus();
}
}
, false);
//Function for checking input text value :
//if the input value is empty, display alert "Your input value must not empty", and put focus in input text.
function check_input_value(event)
{
var event = window.event || event;
if(input_text.value == "")
{
alert("Your input value must not empty");
input_text.focus();
temp = 1;
return false;
}
}
function button_focus()
{
if(input_text.value == "")
{
input_text.focus();
}
temp = 0;
return false;
}
Hope it helps.
This seems to be a bug in Chrome 52 (discussed here). A workaround that came up was to remove the blur event and reattach it in a timeout:
if(input_text.value == "")
{
alert("Your input value must not empty");
var tmpBlur = input_text.blur;
input_text.blur = null;
setTimeout(function() {
input_text.focus();
input_text.blur = tmpBlur;
}, 0);
return false;
}
https://jsfiddle.net/wpys5x75/3/
EDIT:
However it looks like you still get the same infinite loop when you click outside the window. Another work around would be to assign a different value and then reassign the value in the timeout:
if(input_text.value == "")
{
alert("Your input value must not empty");
input_text.value = ' ';
setTimeout(function() {
input_text.focus();
input_text.value = '';
}, 0);
return false;
}
https://jsfiddle.net/wpys5x75/5/
I too faced same issue; I solved it by calling the focus method using setTimeout method.
Code goes as below:
function check_input_value(event)
{
var event = window.event || event;
if(input_text.value == "")
{
alert("Your input value must not empty");
setTimeout (function(){input_text.focus()}, 0);
return false;
}
}

Controlling the submission

I'm trying to stop the submit if an error exists and go through the submission if no error exist.
This is just a section of the code. Regex works correctly, also the error texts were showing up too. The thing is that now I'm trying to control the submit proccess and due to an error (console is not showing up anything) the error text is not showing up and the submission is just going through even if an input error exists.
There is a mistake that I cannot figure out (No jquery please)
var sub = document.querySelector("#register input[type='submit']");//the submit botton
var err_text_1 = "First name must be filled out!";
sub.onsubmit = function(){
if (first_name == null || first_name == "") {
err_holder_1.innerHTML = err_text_1;
return false;
}
else {
err_holder_1.style.display = "none";
}
}
To prevent submit add event in the function and return false like so:
sub.onsubmit = function (event) {
// Will prevent submit
event.preventDefault();
return false;
};
Also select the form you are submitting not the button itself. So:
var sub = document.getElementById('ActionForm');
Hope this helps.
You need to select the form like
var sub = document.querySelector("#register");//If register is your form id Not input[type='submit']

Using substring within input field

I'm using an ID scanner that acts as a keyboard input and I want an input field to listen for the value and substring (or slice) out unnecessary, extra values.
Currently, the ID scanner formats numbers like this: ;708089113=0184?
I want to grab only the 708089113. I want to remove the semi-colon and everything after the 3.
I'm just not sure how to do this automatically. The stripped value should appear in the field before submitting.
Javascript:
var suid = document.getElementById("SUID").value;
var stripSUID = suid.substring(1,10);
document.getElementById("SUID").value = stripSUID;
HTML:
<input name="SUID" id="SUID" type="text" value="">
JSFiddle Link
You can use jQuery for this.
HTML:
<input name="suid" id="suid" type="text" value="">
JavaScript:
$(function() {
$('#suid').change(function() {
var suid = $(this).val();
var stripSUID = suid.split('=');
var stringLength = stripSUID[0].length;
var returnValue = stripSUID[0].substr(1, stringLength);
$(this).val(returnValue);
});
});
jsFiddle update: http://jsfiddle.net/jhjr288o/4/
So you're asking how to listen for a change to the <input>?
var elm = document.getElementById('SUID');
elm.addEventListener('change', function (e) {
var s = this.value, i = s.indexOf('=');
if (i !== -1) {
s = s.slice(1, i);
this.value = s;
}
});
DEMO
The change event fires when the element loses focus
The input event fires every time oldvalue !== newvalue (i.e. for every char typed)
Also note, this code must be run after the Element exists, i.e. wait for the Window's load event

i want to change behaviour even when an option is not changed in dropdown jquery

I have a requirement to include a user input along with dropdown.
I implemented it using .change() method of jquery.
Using .change() function allows me to take the input when i select "Enter value" option.
In order for this code to work again i will have to change the selection. i.e .
When i click on "Enter value" option again, no index will be changed and nothing will happen.
How do i get the focus to the textbox with out changing the selected option.
In short i want the current functionality to work multiple times with out having to select other options.
My code in js fiddle is :
My code in jsfiddle
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
} else {
x.find('.holder').val(x.find('option:selected').text());
x.find('.holder').prop('disabled',true);
}
});
You could change the select value to be "0" and thus show "None" after giving focus to the input field.
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
jQuery(this).val("0"); // Change select value to None.
} else {
x.find('.holder').val(x.find('option:selected').text());
x.find('.holder').prop('disabled',true);
}
});

Categories

Resources