Looking for the best approach to perform a javascript notification pop-up if amount in field A is edited to a smaller amount that what is found in field B?
We aren't using any js frameworks but that option isn't ruled out.
Thanks.
I would recommend jQuery then you could do:
<input id='fld1' type=text value=5>
<div id="label1" style="display:none;"> </div>
<input id='fld2' type=text value=5>
and in your script
$(document).ready(function() {
$('#fld1').change(function(){
if($(this).val()>$('#fld2').val()){
//display it on the form
$('#label1').append('Fld 1 cannot be bigger than fld2!').show();
//or alert it to the user using alert();
alert('Fld 1 cannot be bigger than fld2!');
}
})
});
see http://api.fatherstorm.com/test/4168233.php
You might try using the alert function.
You can use alert function
if(valueOfFieldA < valueOfFieldB)
{
alert('please enter amount greater than Field B');
}
I guess this is what you were looking for.
Code rewritten here for your convenience
HTML
<label>A</label><input type="text" id="input1" onblur="checkBValue()"/><br/>
<label>B</label><input type="text" id="input2"/>
JS
function checkBValue(){
var b=parseInt(document.getElementById("input2").value);
var a=parseInt(document.getElementById("input1").value);
if (a<b && !isNaN(a) && !isNaN(b)) alert("A="+a+ " is less than B="+b);
return;
}
simply, you can create a js function and call it with onchange event of the A input,
so you can specify your special way to notify user ;)
Shameless plug, but here's a library I've written to handle notifications very easily: http://shaundon.github.io/simple-notifications/
Related
I am trying to make a website that validates a specific password and if so it takes the user into my website I can't resolve the bug so can I get some help...?
<script language="Javascript">
function check(x){
if (x == "HI"){
alert("Just Press Ok to Continue...");
} else {
alert("Nope... not gonna happen");
}
}
var grape = alert("Just press Ok to Countinue...")
function alertIt() {
if (grape === true){
window.location="http://www.google.com";
} else {
alert("Nope... not gonna happen")
}
}
}
</script>
<center>
<br /><h3>Enter the Password</h3>
<br />
<b>Password:</b>
<input type="password" id="pass" value="">
<br /><br />
<button onclick="javascript:check(document.getElementById('pass').value)">Check Password</button>
<button onclick="javascript:alertIt">On To my Website</button>
Thank you I am just a kid and still rough on my javascript and I didnt wanna use PHP.
grape will be equal to undefined.
This is because alert() always returns undefined (has no return value).
You want to use confirm() instead.
The main issue with your code is that you have two functions to
accomplish one thing and your second function (alertIt) was based on
a condition that was never going to be true.
Let's take the problems one at a time....
First, you have an extra } just before your </script>
tag. This would result in none of your code even executing. Let's
hope that was just a copy/paste error.
Next, this line: var grape = alert("Just press Ok to
Countinue...") will always result in grape being undefined
because an alert() never returns a value. That being the
case, you can't expect: if (grape === true){ in your alertIt
function to ever be true.
Probably the most significant issue is that your code is overly
complicated for the task you've stated you want to accomplish
"validates a specific password and if so it takes the user into my website". To do this, you really just need the check function.
You can get rid of the alertIt function and the "on to my
website" button.
Next (and this isn't the reason your code didn't work, but it is a
suggestion for best-practices), don't use inline HTML attributes to
wire up events (onclick, onmouseover, onmouseout, etc). They
cause global anonymous wrapper functions to be created, they create
spaghetti code that makes scaling and debugging code harder and they
don't follow W3C DOM Event standards.
Finally (and, again this is just to improve your code), styling
should be done with CSS and not using deprecated HTML (i.e.
<center>).
So, you're adjusted working code now looks like this. Please read the comments within the code for explanations of what is being done and why:
// When the DOM is fully loaded:
window.addEventListener("DOMContentLoaded", function(){
// Get references to the elements that you'll need
var password = document.getElementById("pass");
var btnPassword = document.getElementById("btnCheck");
// Then, instead of wiring HTML elements to JavaScript event callbacks in HTML
// do it with the W3C DOM Event standard of: .addEventListener()
btnPassword.addEventListener("click", function(){
// Call your check function and pass it the password
check(password.value);
});
// This is the only function you need. It combines the old "alertIt" with "check"
function check(x){
if (x == "HI"){
// If the password is correct, tell the user and proceed
alert("Just Press Ok to Continue...");
window.location="http://www.google.com";
} else {
// If not, just tell the user:
alert("Nope... not gonna happen");
}
}
});
/* Write style rules to affect the parts of the document you want */
body { text-align:center; }
#pwd { font-weight:bold; }
<!-- Note that <center> and <b> have been moved into the CSS
because styling should not be done in HTML. Also, note that
<div> and <p> were added for structure and excessive <br> were
removed. Again, don't use HTML for formatting. -->
<div>
<h3>Enter the Password</h3>
<br>
<span id="pwd">Password:</span>
<input type="password" id="pass">
</div>
<p>
<button id="btnCheck">Check Password</button>
</p>
This is great for learning, but anyone can view source and see your password, so it's just for learning... Mmmkay? I've removed all the other logic so we can focus on the question. Once you solve all the issues mentioned by #ScottMarcus and others you should end up with something like this...
function check(x) {
if (x === "HI") {
alert('going to website')
location.assign("#mywebsite");
} else {
alert("Nope... not gonna happen");
}
}
<h3>Enter the Password</h3>
<b>Password:</b>
<input type="password" id="pass" value="">
<button onclick="javascript:check(document.getElementById('pass').value)">Check Password</button>
I apologize if this question has been poorly worded. The reason I'm asking here is because I didn't know how to Google it properly.
Basically, I want the client to be able to specify a number (they could type the number in a textbox or there could be a series of numbers in a drop-down box or even radio buttons, i'm very flexible with this) that determines how many set of questions the form will display.
To put it into context to make it hopefully easier to understand:
-The form is for booking tickets
-If the client chose '1' at the start, it would mean one ticket so only one set of questions would be visible
-If the client chooses 2 then they want to book 2 tickets etc etc.
I'm looking for a method to implement this using html, css and/or jquery/javascript if needed.
Many thanks in advance!
you can use sheepit plugin - sheepit for form cloning
go through it. it can help you a lot.
when user chooses number of seats, make a loop for each seat and repeat questions as needed. all in same form.
using php
for ($question = 0 ; $question < $_POST['SeatNumbers'] ; $question ++) { ... }
You then have to cycle thru the total number set of questions, I'm guessing you probably will use a SeatNumber input, in the above code you'll get a $SeatNumber0, $SeatNumber1 and so on.
Check to see if $SeatNumber exists, and process if it does.
Using JS, I define a max number for the options. and when user changes seat number, I show/hide each question with css "display:none"/"display:inline"
If you want to handle html content dynamically, you'll need to use Javascript.
You can hear event from your text field or your selector used for provide the number of ticket.
Try this with jQuery :
$('your_field_selector').on('change') or this $('your_field_selector').on('keyup')
If the event is triggered, you can get the value of the field with the jQuery method called "val()" :
$('your_field_selector').val()
Next insert your new html content in function of the value.
Here, There's also many jQuery method for do that like "append()","insertBefore()","insertAfter()"... etc
I think this is the sort of thing your after.
The amount of sections within the form is generated by the number selected on the slider with each dynamically generated form element having a unique id depending on which ticket its for ie: ticket 3 has a name id of name3 ticket 14 would have a name id of name14 and so on to allow proper usage of each input through your server side post functionality.
here is a working jsfiddle http://jsfiddle.net/fd78gkf3/
Excuse the generic form field names :)
<script>function showValue(newValue)
{
document.getElementById("tAmount").value = newValue;
document.getElementById("tAmountDisplay").innerHTML = newValue;
}
</script>
<script>
$(document).on("click", '#select', function() {
var formTimes = document.getElementById("tAmount").value;
$('#forms').append('<form id="ticketForm">');
for(var i = 1; i < formTimes; i++) {
$('#forms').append(i);
$('#forms').append('<div id="formPanel">');
$('#forms').append('<label>Name</label><input id="name' + i +'" type="text"/>'+'<br/>');
$('#forms').append('<label>Age</label><input id="age' + i +'"type="text"/>'+'<br/>');
$('#forms').append('<label>Gender</label><input id="gender' + i +'" type="text"/>'+'<br/>');
$('#forms').append('</div>');
}
$('#forms').append('<input type="button" id="submit" value="Submit"/>'+'</form>')
});
</script>
<span id="tAmountDisplay">0</span> Tickets
<form action="" method="post">
<input type="range" min="1" max="20" value="1" step="1" width="100px" oninput="showValue(this.value)" />
<input type="hidden" id="tAmount" name="tAmount" value=""/>
<input type="button" id="select" value="Select" />
<div id="forms">
</div>
</form>
I have a textbox, and I am trying to fire an event oninput (my example below only removes a comma from the input, however I do need it to do more advance things). My code works great on Firefox and Internet Explorer, however when I click into the textbox in Chrome, I have about .5 seconds to start typing, otherwise I loose focus. Testing the exact code below on my website creates the error. Any idea?
<input type="text" id="question" name="question" oninput="clean(this);" />
<script type="text/javascript">
function clean(q){
q.value=q.value.replace(",","");
}
</script>
Thanks for any help
Credit goes to ComFreek and RobH for pointing it out that it works just fine on JS fiddle. I feel quite dumb for not trying it first. Turns out that some of the other Javascript on the page was causing the trigger to break. Thanks for everyone's help!
You can try to set a timer to run the code in the function.
<input type="text" id="question" name="question" oninput="clean(this);" />
<script type="text/javascript">
function clean(q){
window.setTimeout(function(){
q.value=q.value.replace(",","");
}, 0);
}
</script>
Try to use <input onkeyup="clean(this)">, it will only fire the function after something is typed into the input.
http://www.w3schools.com/jsref/event_onkeyup.asp
If you are going to do some complex things I'd recommend you use jQuery, because will fix this crossbrowser errors.
and use something like:
$('#input-desired').bind('keyup', function() {
this.value = this.value.replace(',', '');
});
If you wanna go for a simple application you can try this.
<input type="input" id="desired" onkeyup="desiredInputChanges(this);" />
In your Javascript file use something like:
desiredInputChanges = function (input) {
input.value = input.value.replace(',', '');
}
Just a note, don't forget to make a function to be your class and protect your methods :)
This is probably very simple, but could somebody tell me how to get the cursor blinking on a text box on page load?
Set focus on the first text field:
$("input:text:visible:first").focus();
This also does the first text field, but you can change the [0] to another index:
$('input[#type="text"]')[0].focus();
Or, you can use the ID:
$("#someTextBox").focus();
You can use HTML5 autofocus for this. You don't need jQuery or other JavaScript.
<input type="text" name="some_field" autofocus>
Note this will not work on IE9 and lower.
Sure:
<head>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#myTextBox").focus();
});
</script>
</head>
<body>
<input type="text" id="myTextBox">
</body>
Why is everybody using jQuery for something simple as this.
<body OnLoad="document.myform.mytextfield.focus();">
Think about your user interface before you do this. I assume (though none of the answers has said so) that you'll be doing this when the document loads using jQuery's ready() function. If a user has already focussed on a different element before the document has loaded (which is perfectly possible) then it's extremely irritating for them to have the focus stolen away.
You could check for this by adding onfocus attributes in each of your <input> elements to record whether the user has already focussed on a form field and then not stealing the focus if they have:
var anyFieldReceivedFocus = false;
function fieldReceivedFocus() {
anyFieldReceivedFocus = true;
}
function focusFirstField() {
if (!anyFieldReceivedFocus) {
// Do jQuery focus stuff
}
}
<input type="text" onfocus="fieldReceivedFocus()" name="one">
<input type="text" onfocus="fieldReceivedFocus()" name="two">
HTML:
<input id="search" size="10" />
jQuery:
$("#search").focus();
Sorry for bumping an old question. I found this via google.
Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.
eg.
$('#myform input,#myform textarea').first().focus();
This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.
This is what I prefer to use:
<script type="text/javascript">
$(document).ready(function () {
$("#fieldID").focus();
});
</script>
place after input
<script type="text/javascript">document.formname.inputname.focus();</script>
The line $('#myTextBox').focus() alone won't put the cursor in the text box, instead use:
$('#myTextBox:text:visible:first').focus();
$("#search").focus();
You can also use HTML5 element <autofocus>
The Simple and easiest way to achieve this
$('#button').on('click', function () {
$('.form-group input[type="text"]').attr('autofocus', 'true');
});
I'm rolling my own version of prompt() for aesthetic purposes; it's come along quite nicely as far as visuals go, but I have run into a slight hitch: the native version of the function causes code execution to cease completely until the prompt has been dealt with.
This is positively lovely and it's why the below works the way it does:
<script>
var c = prompt('Name?', '');
alert(c); // displays whatever the user entered
</script>
With my method, however, things do not go as smoothly. I am using a dialog, an input box, and an OK button to gather the data from the user; to my knowledge, data collection works perfectly; that is, I know for sure that after the user presses the OK button, I have access to the data they just put into the prompt.
I cannot, however, find a way to get my version to work as the native one does. My question, then, is this: is it at all possible to tell JavaScript to halt executing until you've told it to resume?
Thanks in advance for any and all assistance.
No, it is not possible to duplicate this behavior. The way to achieve the same effect is to use a callback in your code, so you can do something like:
myPrompt('Hello, mate, whats yer name?', function(answer) {
alert(answer);
});
EDIT: Based on your code, why not do this?
<body>
<div id="prompt" style="display: none;">
<input type="text" id="q" /> <input type="button" value="OK" id="ok" />
</div>
<script>
$ = function(i) {return document.getElementById(i);}
_prompt = function(prompt, callback) {
$('prompt').style.display = '';
$('q').value = '';
$('ok').onclick = function() {
callback($('q').value);
}
}
_prompt('Name?', function(answer) {
alert(answer);
});
</script>
</body>
If you change alert(answer); to say... gAnswer = answer; (notice no var declaration) you would be creating a global variable named gAnswer that you could access anywhere else in the javascript code, assuming the prompt was already answered. If you're concerned of global variables polluting your space you could wrap it all in a closure, but it should be fine otherwise.
#Paolo:
This is the code I am currently working with:
<body>
<div id="prompt" style="display: none;">
<input type="text" id="q" /> <input type="button" value="OK" id="ok" />
</div>
<script>
$ = function(i) {return document.getElementById(i);}
_prompt = function(q, e)
{
$('prompt').style.display = '';
$('q').value = '';
$('ok').setAttribute('onclick', e + ' $("prompt").style.display = "none";');
}
var c; _prompt('Name?', 'c = $("q").value;');
alert(c);
</script>
</body>
Now, as would be expected, that alert() fires as soon as the page is loaded, which is most definitely not what I want; ideally, I'd like for the rest of the code to wait for the prompt to get handled, but I'm strongly doubting this is possible outside of the native implementation. Reckon I'll just have to settle for designing my algorithm so that the prompt gets used immediately?