modal popup displays different text depending on input - javascript

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!

Related

Issues displaying a dynamically updated HTML input value

I'm struggling to get the behaviour I need - as follows:
A HTML form is pre-populated with a value via jQuery. When the user focuses on the input field I want the form to clear. On blur from the form, the form should repopulate the form with the existing value.
I have a solution that clears and repopulates the form but it fails as soon as anything is typed in.
This is what I have so far:
var x = "Default";
$(function () {
$("input").attr({
"value": x
});
$("input").focus(function () {
$("input").attr({
"value": ""
});
});
$("input").blur(function () {
$("input").attr({
"value": x
});
});
});
https://jsfiddle.net/thepeted/p74kfdt8/6/
If I look in developer tools, I can see the input value is changing dynamically in the DOM, but in the case that the user has typed something in to the form, the display no longer updates.
I'd love to understand why this is happening (ie, why it works in one case and not the other). Also, if there is a better way of approaching the problem.
As pointed out by Stijn, best practice would be to use the placeholder attibute.
However if you do want to use a function for it. I would check on the focus if the value is the default value or not. If so, empty the input, if not, don't do anything.
On blur, you also only want to place the default value back if the value is empty... so check for that aswell.
var x = "Default";
$(function() {
$('input[type=text]').val(x);
$('input[type=text]').on('focus', function() {
var elem = $(this);
if (elem.val() == x)
elem.val('');
}).on("blur", function() {
var elem = $(this);
if (elem.val() == '')
elem.val(x);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
Your edited jsfiddle.
updated code:
$("input").blur(function () {
$("input").val(x);
});
Personnaly, I'd use the placeholder attribute as everyone pointed out. If you too are facing the need to support older browsers and some others that do not support the placeholder attribute, use this snippet I've made:
$('input[placeholder]').each(function(){
var $this = $(this);
$this.val($this.attr('placeholder')).css('color','888888');
$this.focus(function(){
if($(this).val() == $(this).attr('placeholder'))
$(this).val('').css('color','');
});
$this.blur(function(){
if($(this).val() == '')
$(this).val($(this).attr('placeholder')).css('color','888888');
});
});
This script will find all inputs with a placeholder attribute, give it's value to the input, and add the correct events. I've left the css calls just to show you where to put the codes to mimic the greyed text like modern browsers do.
Try this code
var x = "Default";
$(function () {
$("input").val(x);
$("input").focus(function () {
$("input").val("");
});
$("input").blur(function () {
$("input").val(x);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>

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

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

Conflict with JS - targets first expander and not the one clicked.

I have a link that expands to reveal a div when clicked - however, if I have more than one on a page, if I click for eg. the third, it'll open the top one. How do I target the one clicked rather than the first/highest on the page.
$("body").on("click", ".show-hidden", function() {
var $link = $(this);
var $slidingElement = $($link.attr("href"));
if( !$slidingElement.is(':animated') ) {
$link.toggleClass("shown");
$slidingElement.slideToggle( 700 );
}
return false;
JSFiddle: http://jsfiddle.net/TrueBlueAussie/j4wDL/1/
This one works. Can you explain how your layout differs from the mockup I have provided?
$(document).on("click", ".show-hidden", function () {
var $link = $(this);
var $slidingElement = $($link.attr("href"));
if (!$slidingElement.is(':animated')) {
$link.toggleClass("shown");
$slidingElement.slideToggle(700);
}
return false;
});
The most likely cause is incorrect hrefs as they would need to include a valid JQuery selector (e.g. href="#one")

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/

Prevent click event in jQuery triggering multiple times

I have created a jQuery content switcher. Generally, it works fine, but there is one problem with it. If you click the links on the side multiple times, multiple pieces of content sometimes become visible.
The problem most likely lies somewhere within the click event. Here is the code:
$('#tab-list li a').click(
function() {
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow');
}
);
}
return false;
}
);
I have tried adding a lock to the transition so that further clicks are ignored as the transition is happening, but to no avail. I have also tried to prevent the transition from being triggered if something is already animating, using the following:
if ($(':animated')) {
// Don't do anything
}
else {
// Do transition
}
But it seems to always think things are being animated. Any ideas how I can prevent the animation being triggered multiple times?
One idea would be to remove the click event at the start of your function, and then add the click event back in when your animation has finished, so clicks during the duration would have no effect.
If you have the ability to execute code when the animation has finished this should work.
Add a variable to use as a lock rather than is(:animating).
On the click, check if the lock is set. If not, set the lock, start the process, then release the lock when the fadeIn finishes.
var blockAnimation = false;
$('#tab-list li a').click(
function() {
if(blockAnimation != true){
blockAnimation = true;
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow', function(){ blockAnimation=false; });
}
);
}
}
return false;
}
);
Well this is how i did it, and it worked fine.
$(document).ready(function() {
$(".clickitey").click(function () {
if($("#mdpane:animated").length == 0) {
$("#mdpane").slideToggle("slow");
$(".jcrtarrow").toggleClass("arrow-open");
}
});
});
this is not doing what your code does ofcourse this is a code from my site, but i just like to point how i ignored the clicks that were happening during the animation. Please let me know if this is inefficient in anyway. Thank you.
I toyed around with the code earlier and came up with the following modification which seems to work:
$('#tab-list li a').click(
function() {
$('.tab:animated').stop(true, true);
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow');
}
);
}
return false;
}
);
All that happens is, when a new tab is clicked, it immediately brings the current animation to the end and then begins the new transition.
one way would be this:
$('#tab-list ul li').one( 'click', loadPage );
var loadPage = function(event) {
var $this = $(this);
$global_just_clicked = $this;
var urlToLoad = $this.attr('href');
$('#content-area').load( urlToLoad, pageLoaded );
}
$global_just_clicked = null;
var pageLoaded() {
$global_just_clicked.one( 'click', loadPage );
}
As you can see, this method is fraught with shortcomings: what happens when another tab is clicked before the current page loads? What if the request is denied? what if its a full moon?
The answer is: this method is just a rudimentary demonstration. A proper implementation would:
not contain the global variable $global_just_clicked
not rely on .load(). Would use .ajax(), and handle request cancellation, clicking of other tabs etc.
NOTE: In most cases you need not take this round-about approach. I'm sure you can remedy you code in such a way that multiple clicks to the same tab would not affect the end result.
jrh.
One way to do this to use timeStamp property of event like this to gap some time between multiple clicks:
var a = $("a"),
stopClick = 0;
a.on("click", function(e) {
if(e.timeStamp - stopClick > 300) { // give 300ms gap between clicks
// logic here
stopClick = e.timeStamp; // new timestamp given
}
});

Categories

Resources