What is wrong with my JavaScript code? (Search bar) - javascript

I have some code here in JS and I can't figure out why it isn't doing what I want it to do. Basically, I have a search bar that should write "Search..." it in. When the user clicks on it, the text goes away and the bar goes blank. If the user clicks away without filling any text in, the "Search..." text returns.
Otherwise, the text the user enters stays in the bar. Up until this point my code works fine. The issue is this; when the user inputs something AND THEN takes it away, the bar remains blank, whereas the "Search..." text should return. (Notice: This does not occur if the user simply clicks on the bar and then clicks away; the default text returns as it should. It only happens if the users enters something and then takes it away.)
I can not figure out why this is happening. Any help would be greatly appreciated. Here is my JS code:
$(document).ready(function () {
var search_default = 'Search...';
$('input[type="search"]').attr('value', search_default).focus(function () {
if ($(this).val() == search_default) {
$(this).attr('value', '');
}
}).blur(function () {
if ($(this).val() == '') {
$(this).attr('value', search_default);
}
});
});

Use .val(value) instead of attr('value',value)
$(document).ready(function () {
var search_default = 'Search...';
$('input[type="search"]').val(search_default).focus(function () {
if ($(this).val() == search_default) {
$(this).val('');
}
}).blur(function () {
if ($(this).val() == '') {
$(this).val(search_default);
}
});
});

If you can edit the HTML, this is how i would do it:
JSFIDDLE DEMO - EDITED HTML
If you cannot edit the HTML, you would need to create the data-default attribute
JSFIDDLE DEMO 2 - NON EDITED HTML
Add a data-default tag to the element
<input type="search" data-default="Search..." value="Search...">
And the jQuery
$(document).ready(function(e){
// when you focus on the search input
$('input[type=search]').on('focus',function(e){
// if the value is the same as the default value
if( $(this).val() == $(this).attr('data-default') )
{
// make the value blank
$(this).val('');
}
// when you move out of the search input
}).on('blur',function(e){
// if there is no value (blank)
if( !$(this).val() )
{
// add back the default value
$(this).val( $(this).attr('data-default') );
}
});
});

Related

modal popup displays different text depending on input

So I am attempting to have a modal popup that displays two messages depending on what the user types into the text box. I want the script to check whether the input contains one of two strings, either ME, or TN (as I am looking at doing a postcode checker).
no matter what i try I can't get the popup to display two messages depending on the input. I don't want the form to submit, I just want to grab the contents of what has been typed.
Here's a link to what I have so far (imagine the close icon is in the top right)..
$(document).ready(function () {
var formResult = $('#postcode-form')
var postcodeMe = /^[me]+$/;
$("#postcode-form").click(function () {
if (formResult.val().indexOf(postcodeMe)) {
$("#basic-modal-content").html("<h2>Yes it works</h2>")
} else {
$("#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
http://www.muchmorecreative.co.uk/modal_test/basic-modal-testing-jquery-conditions/
try this:
$(document).ready(function() {
var formResult = $('#postcode-form')
var postcodeMe= /^[me]+$/;
$( "#postcode-form" ).click(function(e) {
e.preventDefault();
if ($(this).val().contains(postcodeMe)){
$( "#basic-modal-content").html("<h2>Yes it works</h2>")
}
else {
$( "#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
The problem is you're setting formResult as a 'global' variable (sorta). It gets its value when the page loads and never changes. You should change your code to get the value when you actually need it, not immediately after page load.
$(document).ready(function () {
var postcodeMe = /^[me]+$/;
$("#postcode-form").click(function () {
//move it to here so that you get the value INSIDE the click event
var formResult = $('#postcode-form')
if (formResult.val().indexOf(postcodeMe)) {
$("#basic-modal-content").html("<h2>Yes it works</h2>")
} else {
$("#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
A few other minor things to consider:
indexOf returns a number. You should probably do indexOf(postcodeMe) >= 0
You can look at index of HERE
Have tried these two but not happening, played around with it and found a solution..
$(document).ready(function() {
var formResult = $('#postcode-input')
$( "#postcode-button" ).click(function(e) {
e.preventDefault();
if ($('#postcode-input').val().indexOf("ME")!==-1 || $('#postcode- input').val().indexOf("me")!==-1 ){
// perform some task
$( "#basic-modal-content").html("<h2>Yes it works</h2>")
}
else {
$( "#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
Thanks for the help though!

How to validate a memorized value in an input box

I have the following code:
$(":input").bind("keyup change", function(e) {
var comboVal = $('.emailrequerido1').val()+$('.emailrequerido2').val()+$('.emailrequerido3').val()+$('.emailrequerido4').val()+$('.emailrequerido5').val();
if(comboVal == 'nullnull' || comboVal == ""){
$("#enviarForm").attr('disabled', true);
}else{
$("#enviarForm").removeAttr('disabled');
}
});
What I am trying to accomplish is that when you select a memorized value from the input box by double clicking in the box a history of inputs shows (these values are saved by the browser (I believe)) and if you choose one of these and the field has that text you selected the button should enable.
Here is a JSFiddle example: JSFiddle example
In the example I added a value to the first field since these dont memorize as I expalined before to show a demonstration of what I mean.
I have cleaned up the code a bit: http://jsfiddle.net/kam5B/1/
I've swapped the classes and ids so that the ids are unique, and the classes are common.
Here is a checkEmails function that runs the validation and enables/disables the checkbox.
checkEmails is run every time an input changes, and when the page loads the first time:
$(document).ready(function () {
function checkEmails() {
var nonempty = $('form .email_contactopadrino').filter(function() {
return $(this).val() != '';
});
if (nonempty.length) {
$('#enviarForm').removeAttr('disabled');
}
else {
$('#enviarForm').attr('disabled', true);
}
};
$('form').on('keyup change', '.email_contactopadrino', checkEmails);
checkEmails();
});

Click off input area function using jQuery

I have an input field I want cleared. My jQuery works there but if I click the input field and then click off of it the value is back. What's the fix?
$('input').val('');
$('input').click( function() {
$('input').val('');
});
JS fiddle here. http://jsfiddle.net/thomasp423/HqvmD/
It seems that normally the one line I have would work BUT I'm working with some software that probably has js overriding this and adding it back on. Does anyone have a solution?
$('input').click( function() {
$(this).val('');
});
What you're saying is: clear all inputs when clicked on one input.
I think this is what you are looking for http://jsfiddle.net/HqvmD/1/
//$('input').val('');
$('input').focus( function() {
if ($(this).val() == 'search' ) {
$(this).val('');
}
});
$('input').focusout(function () {
if ($(this).val() == '' ) {
$(this).val('search');
}
});

Global click event blocks element's click event

This should happen
If the user clicks on one of the two input boxes, the default value should be removed. When the user clicks elswhere on the webpage and one text field is empty, it should be filled with the default value from the data-default attribute of the spefic element.
This happens
When somebody clicks somewhere on the page and the field is empty, the field will be filled with the right value, but when somebody clicks in the field again the text isn't removed. It seems like the $(document) click event is blocking the $(".login-input") click event, because the $(".login-input") is working without the $(document) click event.
JSFiddle
A sample of my problem is provieded here: JSFiddle
Tank you for helping!
When you click on the input, the script is working, but since the input is in the document, a click on the input is a click on the document aswell. Both function will rune, document is the last one.
That is called event bubblingand you need to stop propagation :
$(document).ready(function () {
$(".login-input").click(function (e) {
e.stopPropagation()
$(this).val("");
});
});
Fiddle : http://jsfiddle.net/kLQW9/3/
That's not at all how you solve placeholders, you do it like so :
$(document).ready(function () {
$(".login-input").on({
focus: function () {
if (this.value == $(this).data('default')) this.value = '';
},
blur: function() {
if (this.value == '') this.value = $(this).data('default');
}
});
});
FIDDLE
Preferably you'd use the HTML5 placeholder attribute if really old browsers aren't an issue.
EDIT:
if you decide to do both, check support for placeholders in the browser before applying the javascript :
var i = document.createElement('input'),
hasPlaceholders = 'placeholder' in i;
if (!hasPlaceholders) {
// place the code above here, the condition will
// fail if placeholders aren't supported
}
Try below code
$(document).ready(function () {
$(".login-input").click(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").each(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
Check fiddle
Why not to use focus and blur events?
$(document).ready(function () {
$(".login-input").focus(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
http://jsfiddle.net/kLQW9/5/
P.S. In yours, and this code, on focus all data fro input will be cleared. If you need to clear only default text, add proper condition for that.

How can I update a input using a div click event

I've got the following code in my web page, where I need to click on the input field and add values using the number pad provided! I use a script to clear the default values from the input when the focus comes to it, but I'm unable to add the values by clicking on the number pad since when I click on an element the focus comes from the input to the clicked number element. How can I resolve this issue. I tried the following code, but it doesn't show the number in the input.
var lastFocus;
$("#test").click(function(e) {
// do whatever you want here
e.preventDefault();
e.stopPropagation();
$("#results").append(e.html());
if (lastFocus) {
$("#results").append("setting focus back<br>");
setTimeout(function() {lastFocus.focus()}, 1);
}
return(false);
});
$("textarea").blur(function() {
lastFocus = this;
$("#results").append("textarea lost focus<br>");
});
Thank you.
The first thing I notice is your selector for the number buttons is wrong
$('num-button').click(function(e){
Your buttons have a class of num-button so you need a dot before the class name in the selector:
$('.num-button').click(function(e){
Secondly, your fiddle was never setting lastFocus so be sure to add this:
$('input').focus(function() {
lastFocus = this;
...
Thirdly, you add/remove the watermark when entering the field, but ot when trying to add numbers to it (that would result in "Watermark-text123" if you clicked 1, then 2 then 3).
So, encalpsulate your functionality in a function:
function addOrRemoveWatermark(elem)
{
if($(elem).val() == $(elem).data('default_val') || !$(elem).data('default_val')) {
$(elem).data('default_val', $(elem).val());
$(elem).val('');
}
}
And call that both when entering the cell, and when clicking the numbers:
$('input').focus(function() {
lastFocus = this;
addOrRemoveWatermark(this);
});
and:
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
addOrRemoveWatermark(lastFocus);
$(lastFocus).val($(lastFocus).val() + $(this).children('span').html());
});
You'll see another change above - you dont want to use append when appends an element, you want to just concatenate the string with the value of the button clicked.
Here's a working branch of your code: http://jsfiddle.net/Zrhze/
This should work:
var default_val = '';
$('input').focus(function() {
lastFocus = $(this);
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
var lastFocus;
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
var text = $(e.target).text();
if (!isNaN(parseInt(text))) {
lastFocus.val(lastFocus.val() + text);
}
});
Live demo
Add the following function:
$('.num-button').live( 'click', 'span', function() {
$currObj.focus();
$currObj.val( $currObj.val() + $(this).text().trim() );
});
Also, add the following variable to global scope:
$currObj = '';
Here is the working link: http://jsfiddle.net/pN3eT/7/
EDIT
Based on comment, you wouldn't be needing the var lastFocus and subsequent code.
The updated fiddle lies here http://jsfiddle.net/pN3eT/28/

Categories

Resources