Change the onblur event of a text field - javascript

I have a text box for typing names inside a form.A div below the text box shows names of registered users from the database with the help of AJAX starting with the letters typed by the user.The user can also click on the usernames and those names will be placed in the text box.Also the div will get disappear.I have written onblur event for the text box so that on losing the focus for the text box,the div created below should disappear.This works for me.My issue is that i cant select the names from the div below ,since on blur event fires.I need onblur event because all other events other than selecting username function requires this on blur event.
My code is like this:
<input id="venue" type="text" onkeyup="showData(this.value)"
onblur="return removediv()"/>
<div id="venuesearch">
</div>//div for displaying the set of usernames with help of AJAX
My javascript code is:
function showData(str)
{
if (str.length==0)
{
document.getElementById("venuesearch").innerHTML = "";
document.getElementById("venuesearch").style.border = "0px";
return;
}
// some AJAX code here
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("venuesearch").innerHTML=xmlhttp.responseText;
document.getElementById("venuesearch").style.border="1px solid #A5ACB2";
document.getElementById("venuesearch").style.display="block";
document.getElementById("venuesearch").style.overflow="show";
}
xmlhttp.open("GET","search_venue.php?venue="+str,true);
xmlhttp.send();
}
Inside search_venue.php
There is a method called showVal() on onClick event of the column .
function showVal(val)
{
document.getElementById("venue").value = val;
document.getElementById("venuesearch").style.display = "none";
}
function removediv()
{
document.getElementById("venuesearch").style.display="none";
return false;
}

try this :
function removediv()
{
document.getElementById("venuesearch").style.display="none";
var venue = document.getElementById("venue").value;
return false;
}

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;
}
}

Submit button doesn't run function in panel add-on sdk

I am developing an add on using mozilla's add-on sdk. I have a panel attached to a toggle button that contains one input text box and a submit button. When the user presses enter, I am able to get my function to work. However, when I press the submit button nothing happens. Why is this? I have attached my code below:
// When the user hits return, send the "text-entered"
// message to main.js.
// The message payload is the contents of the edit box.
var textArea = document.getElementById("numTimes");
textArea.addEventListener('keyup', function onkeyup(event) {
if (event.keyCode == 13) {
// Remove the newline.
text = textArea.value.replace(/(\r\n|\n|\r)/gm,"");
self.port.emit("text-entered", text);
textArea.value = '';
console.log("Got text from enter");
}
}, false);
// Listen for the "show" event being sent from the
// main add-on code. It means that the panel's about
// to be shown.
//
// Set the focus to the text area so the user can
// just start typing.
self.port.on("show", function onShow() {
textArea.focus();
});
var submit = document.getElementById("search");
submit.addEventListener("click", function submit(){
text = textArea.value.replace(/(\r\n|\n|\r)/gm,"");
self.port.emit("text-entered", text);
textArea.value = '';
console.log("Got text from submit button");
}, false);
The code that's within the textArea section works but the code by the submit section doesn't. Does JavaScript treat these differently?

How to get focus on a single textbox except on some conditions?

I want to set the focus in a single textbox and some text must be entered in the textbox to move the focus out of it. But there is an exception that I should be able click on the buttons on the page without any entry in that textbox.
Here is what I have done using JavaScript...
function Validate() {
var field1 = document.getElementById('<%=textbox.ClientID %>').value;
if (field1 == "") {
alert("Please Enter some value");
document.getElementById('<%=textbox.ClientID %>').focus();
return false;
}
else {
return true;
}
}
And I have called it like...
onblur="return Validate();"
This is the Script. (jquery required)
$(function() {
$('input[id=word]').blur(function() {
var txtClone = $(this).val();
if(txtClone=="")$(this).focus();
});
});
and here is a html tag
<input type='text' id='word' name='word'>
As you've asked, focus won't move away unless you entered some text and able to click on button outside.

Show button if input is not empty

I am not much of a JavaScript guru, so I would need help with a simple code.
I have a button that clears the value of an input field.
I would like it (the button) to be hidden if input field is empty and vice versa (visible if there is text inside the input field).
The solution can be pure JavaScript or jQuery, it doesn't matter. The simpler, the better.
$("input").keyup(function () {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function () {
$("input").val('');
$(this).hide();
});
http://jsfiddle.net/SVxbW/
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
In it's simplest form ;)
to do this without jQuery (essentially the same thing others already did, just pure js). It's pretty simple, but I've also added a few comments.
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>​
Note: I've written and tested this in IE9 and Chrome, make sure you test it in other browsers. Also, I've added this fiddle so you can see it working.
You can use $('selector').hide() to hide an element from view and $('selector').show() to display it again.
Even better, you can use $('selector').toggle() to have it show and hide without any custom logic.
First hide the button on page load:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
Then attach an onChange handler, which will hide the button whenever the contents of the text-field are empty. Otherwise, it shows the button:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
You will also need to hide the button after clearing the input:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});

Categories

Resources