<form>
<fieldset>
Password: <span id="capsalert">CAPS LOCK = on</span><br>
<input type="password" id="pwd">
<script type="text/javascript">
document.write(
'<input type="checkbox" name="masking" onclick="unmask(this.checked)"> ' +
'Show the password as I type'
);
</script>
<br>
Password2:<br>
<input type="password" id="pwd2">
</fieldset>
</form>
<script type="text/javascript">
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !!(ev.modifiers & 4) : false));
if(
(kc >= 97 && kc <= 122 && sk) ||
(kc >= 65 && kc <= 90 && !sk)
) {
document.getElementById('capsalert').style.display = 'inline';
}
else {
document.getElementById('capsalert').style.display = 'none';
}//end if
}//end function
function unmask(truefalse) {
oldElem = document.getElementById('pwd');
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById('pwd').value);
elem.id = 'pwd';
oldElem.parentNode.replaceChild(elem,oldElem);
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
}//end function
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
</script>
I'm using the above code in a slightly more complex form.
I have two separate "password" fields on the form. With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.
Also, the code notifies the user if they are typing with CAPS Lock enabled.
I would like to have both password fields exhibiting the same behavior rather than the first field only. Unfortunately, I do not know how to make that happen.
Thanks for the help.
EDIT:
A simple solution might be easier to find with the following code. I'm willing to use either one.
<script>
function changeType()
{
document.myform.pass.type=(document.myform.option.value=(document.myform.option.value==1)?'-1':'1')=='1'?'password':'text';
}
</script>
<body>
<form name="myform">
<input type="password" name="pass" />
<input type="password" name="pass2" />
<input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>
</body>
Why don't you just change the type attribute of the password inputs in your unmask() function? That way it will be easier for you to manage more than 1 field. After checking whether you have to turn the input into a text one or a password one, do this:
// Suppose 'new_type' is either 'text' or 'password'
// and that 'pwd' and 'pwd2' are the id attributes for
// both of your password fields
document.getElementById('pwd').type = new_type;
document.getElementById('pwd2').type = new_type;
I suggest changing your approach a bit.
You could modify the client with no impact to the server code. For example, I would try using 2 input boxes with the same name. If you ever have one box visible while the other one has the 'disabled' HTML attribute set, the visible box will always be the only one submitted.
This way, your server-side code would only have to look for 1 input, under a single name.
jQuery caps lock test/function?
set both fields to class of password and:
jQuery('.password').caps(function(caps){
if(jQuery.browser.safari) return; // Safari already indicates caps lock
// "this" is current element
if(caps){
alert('Your caps lock is on!');
}else{
// no caps lock on
}
});
Try this:
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !! (ev.modifiers & 4) : false));
if ((kc >= 97 && kc <= 122 && sk) || (kc >= 65 && kc <= 90 && !sk)) {
document.getElementById('capsalert').style.display = 'inline';
} else {
document.getElementById('capsalert').style.display = 'none';
}
//end if
}
//end function
function unmask(truefalse) {
for (var f in new Array('pwd', 'pwd2')) {
oldElem = document.getElementById(f);
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById(f).value);
elem.id = f;
oldElem.parentNode.replaceChild(elem, oldElem);
document.getElementById(f).onkeypress = function (e) {
chkCaps(e);
};
}
}
//end function
document.getElementById('pwd').onkeypress = function (e) {
chkCaps(e);
};
document.getElementById('pwd2').onkeypress = function (e) {
chkCaps(e);
};
What this does is make it so your code works on pwd and pwd2 by repeating it for each element in the array new Array('pwd', 'pwd2').
Most of the answers didn't work. One or two I left untried because they meant greater changes to my code than I wanted. I ended up finding yet another method to reveal the passwords: "Show password as text" control
I adapted the method there to my multiple password fields scenario:
<input type="checkbox" onchange="document.getElementById('gpwd').type = this.checked ? 'text' : 'password'; document.getElementById('pwd1').type = this.checked ? 'text' : 'password'; document.getElementById('pwd2').type = this.checked ? 'text' : 'password'"> Reveal passwords
Related
I can not make a search using this check boxes. When I run the code (check), nothing happens. I have to check it for make an advance search and it will select data from database.
My HTMLcode:
<td><input type="checkbox" name="fac1" value="checked"/>AIRCOND</td>
<td><input type="checkbox" name="fac2" value="checked"/>FAN</td>
My PHP code:
$fac1=isset($_POST["fac1"]);
$fac2=isset($_POST["fac2"]);
$qry = "SELECT * FROM homestay WHERE ";
if(isset($_POST['fac1']) && $_POST['fac1'] == 'checked')
{
$fac1 = true;
}
if(isset($_POST['fac2']) && $_POST['fac2'] == 'checked')
{
$fac2 = true;
}
$string = isset($_POST['fac1']) ? $_POST['fac1'] : (isset($_POST['fac2']) ? $_POST['fac2'] : '');
OR
if(isset($_POST['fac1']) && $_POST['fac1'] == 'checked')
{
$string = $fac1;
}
if(isset($_POST['fac1']) && $_POST['fac2'] == 'checked')
{
$string = $fac2;
}
Pass your string variable in query:
$qry = "SELECT * FROM homestay WHERE $string = 'true'";
Doing it like as Ronak suggested would result in a way too long code for multiple search options. Not counting that you have to save every option checked next time you load the page with one option checked.
You could simplify this with ajax, so that it would display the results in your div for example.
first make a form:
<form id="searchOptions">
<td><input type="checkbox" name="fac1" value="checked"/>AIRCOND</td>
<td><input type="checkbox" name="fac2" value="checked"/>FAN</td>
</form>
Then put the script in header:
<script>
function submitSearchForm() {
$.ajax({type:'POST', url: 'search.php', data:$('#searchOptions').serialize();?>, success: function(response) {
$('#resultDisplay').innerHTML = response;
}});
return false;
}
</script>
Notice:
You will also need jquery.min in header
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Hello, I want a popup when the value of my input changes. I tried this, my test of my input :
<input onchange="maFonction()" id="result" readonly="readonly" type="text" value="0" size = "10" />
my function
maFonction = function(){
$.post("yourFile.php");
}
yourfile.php
<?php
$a = 40 ;
if ($result > $a) {
?>
<script> alert("yay!"); </script>
<?php } elseif ($result == $a) {
?>
<input onclick="s(this.form);" type="button" value="sauvegarder" />
<?php
} else {
?>
<script> alert("boooo!"); </script>
<?php
}
?>
I explain the readonly : it is like a calculator : I have many (7) inputs, I can stock values and the readonly is the total. So I need a msg when it is under 40, when it is equal, and when it is over 40.
Thanks for help cause for the moment I don't have any error I just have the popup boo when my page refreshes after nothing.
As I said in my remark, you don't need server-side code to do this. Here's a fiddle to do it with jQuery. Very easy :
HTML :
<input type="text" id="myInput"/>
Javascript (supposing you included jQuery) :
$('document').ready(function() {
$('#myInput').on('change',function(){
if(isNaN(this.value))
alert("Please enter a number");
else
{
var a = 40;
var myNumber = parseInt(this.value);
if(myNumber > a) alert("yay!");
else if (myNumber == a) alert("equals!");
else alert("boooo!");
}
});
});
I think the code is quite easy to understand. Note that you have to leave the text field for the "change" event to trigger, and it supposes you actually changed something. You could use blur event if you want to trigger each time and not only when value changed.
If you want or need to do that kind of check server-side (it may not be that easy than comparing 2 numbers), you can indeed use AJAX. But in that case I would advise to return XML , JSON or even an unformatted string from your server-side code, and treat the response in javascript. For example, you could return simply 'bigger', 'smaller','equal' , and act accordingly in the success event of your AJAX call. But that's for another lesson ;-)
EDIT following remark of OP :
HTML
<input type="text" id="input1" /><br/>
<input type="text" id="input2" /><br/>
<input type="text" id="input3" /><br/>
<input type="text" id="myInput" readonly="readonly"/>
Javascript :
$('document').ready(function() {
$('#input1,#input2,#input3').each(function() {$(this).on('change',recalculate);}
);
});
function recalculate()
{
if(isNaN(this.value))
alert("Please enter a number");
else
{
var a = 40;
var value1 = $('#input1').val().trim() == "" ? 0 : parseInt($('#input1').val());
var value2 = $('#input2').val().trim() == "" ? 0 : parseInt($('#input2').val());
var value3 = $('#input3').val().trim() == "" ? 0 : parseInt($('#input3').val());
var total = value1 + value2 + value3
$('#myInput').val(total);
if(total > a) alert("yay!");
else if (total == a) alert("equals!");
else alert("boooo!");
}
}
The fiddle
And if you wish to calculate and alert only when all 3 fields have been filled :
$('document').ready(function() {
$('#input1,#input2,#input3').each(function() {$(this).on('change',recalculate);}
);
});
function recalculate()
{
if(isNaN(this.value))
alert("Please enter a number");
else
{
if($('#input1').val().trim() !== "" && $('#input2').val().trim() !== "" && $('#input3').val().trim() !== "")
{
var a = 40;
var value1 = $('#input1').val().trim() == "" ? 0 : parseInt($('#input1').val());
var value2 = $('#input2').val().trim() == "" ? 0 : parseInt($('#input2').val());
var value3 = $('#input3').val().trim() == "" ? 0 : parseInt($('#input3').val());
var total = value1 + value2 + value3
$('#myInput').val(total);
if(total > a) alert("yay!");
else if (total == a) alert("equals!");
else alert("boooo!");
}
}
}
The fiddle
i've created exception using JS so that user are only allowed to input numbers to the html form field. this is working nicely but the problem is, the Submit button isn't working anymore. if i remove the exception code, submit button is working nicely! i can't understand where is the problem. anyone can help please? thanks in advance!
here is the exception:
function validateNum(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate()
{
if( document.myForm.ic.value == "" ||
isNaN( document.myForm.ic.value ) ||
document.myForm.ic.value.length != 12)
{
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;
}else{
// Put extra check for data format
var ret = validateNum();
if( ret == false )
{
return false;
}
}
here is my html form action:
<form name="myForm" method="post" action="nonuum_reg.php" onsubmit="return(validate());">
and here is the input field & submit button:
<input name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
<input type="submit" value="Apply" />
Try this one as my explanation on my comment on your question:
<form name="myForm" method="post" action="nonuum_reg.php" onsubmit="validate(event);">
<input name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
<input type="submit" value="Apply" />
</form>
<script>
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == "" || isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12) {
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;
}
}
</script>
You should still create validation on your PHP controller to prevent if users turn off javascript on theirs browser.
Try adding a return true in you =r else close
...
else{
// Put extra check for data format
var ret = validateNum();
if( ret == false )
{
return false;
}
return true;
}
...
This should also help you (not the same issue but same code)link:
I have an HTML page on the admin site for managing user on a HTML/Javascript/PHP system that runs on browsers. I have close to 20 inputboxes because on one page i have combined several forms of new_user, forgot_password, Change_password and Edit_user_details.
This code is what i used to check the username's empty field, this means i have to write 20 of this lines;
My concern is--> How do i write a short, summarized but effective javascript code to check on empty fields. (I will also need to validate fields like digits, numbers, length, emails etc)
function RequiredFields(){
var username=document.forms["login"]["username"].value;
if (username==""||username==null){
alert("empty username")
document.login.username.focus();
if(document.all||document.getElementById){
document.login.username.style.background="pink";
}
return false;
}
}
You can use jQuery to check for empty fields, have a look at this code:
function Validate() {
$('form input[type="text"]').each(function(){
if (this.value=="")
alert('Value Required');
});
}
To validate things like emails, numbers etc, you would need to write a separate function for those particular text boxes.
See here: http://jsfiddle.net/TgCbB/1/
HTML
<input type="text" id="username" class="required" data-default="User Name"/>
<input type="text" id="email" class="required email" data-default="Email"/>
<input type="text" id="digits" class="required digits" data-default="Integer"/>
The important thing to note here is the class attribute, which indicates how it should be validated. (You could do this with a data- attribute, which would be better, but I used class for backwards compatibility).
You can now, with plain javascript, validate like so:
function validate(e){
var invalid = [];
var required = document.getElementsByClassName("required");
for (var i = 0; i < required.length; i++){
var req = required[i];
var val = req.value || "";
var def = req.hasAttribute("data-default") ? req.getAttribute("data-default") : "";
if (val == "" || val == def)
invalid.push(req);
req.className = req.className.replace(" invalid","");
}
var digits = document.getElementsByClassName("digits");
for (var i = 0; i < digits.length; i++){
var dig = digits[i];
var val = Number(dig.value || "");
var rem = val - Math.floor(val);
if (rem != 0)
invalid.push(dig);
dig.className = dig.className.replace(" invalid","");
}
var emails = document.getElementsByClassName("email"),
reg = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
for (var i = 0; i < emails.length; i++){
var em = emails[i];
var val = em.value || "";
if (!reg.test(val))
invalid.push(em);
em.className = em.className.replace(" invalid", "");
}
for (var i = 0; i < invalid.length; i++){
var inp = invalid[i];
var cls = inp.className.replace(" invalid", "");
inp.className = cls + " invalid";
}
}
Note that the could be made less verbose, but I opted for readability. The concept is, get each item with the class name we're validating against, iterate over them, and then mark it as invalid if it doesn't pass validation.
Help with this criteria ?
Users can be able to add as many Names as they want, ADD NAME link serves the purpose for this.
How can I handle this specification ?
Please check the spec below:
Thanks.
var input = $('#input').clone().attr('name', 'name2').attr('id', 'input-2').appendTo('body')
You can go further and clone the entire row/div with $(el).clone() and then do .find('input') and modify the name and id attribute values so they're unique and don't conflict. You can pass true to clone if you want to copy the event handlers.
Incomplete non-jQuery "solution" since I don't know exactly at which point the OP is in since he claims he can clone nodes now..
<div id="wrap">
<div class="foo">
<label for="first_name">name:</label><input type="text" name="first_name[] " id="first_name">delete
</div>
add name
</div>
<script>
(function() {
var add = document.getElementById('add'), counter = 0;
add.onclick = function() {
var rows = document.getElementsByTagName('div'), last = false;
if ( rows.length ) {
for ( var i = rows.length; i--; ) {
if ( last ) { break; }
if ( rows[i].className.length && ( ' ' + rows[i].className + ' ' ).indexOf(' foo ') != -1 ) {
last = rows[i];
}
}
}
if ( last ) {
var newNode = last.cloneNode(true), wrap = document.getElementById('wrap'), input = newNode.getElementsByTagName('input');
input.id = input.id + (counter++);
wrap.appendChild( newNode );
}
}
})();
Hope this goes well.
<html>
<script type="text/javascript">
function addfieldset() {
var namefieldset = document.getElementById("name").cloneNode(true);
document.getElementById("names").appendChild( namefieldset );
}
function deletefieldset( e ) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild( namefieldset );
}
</script>
<body>
<div id="names"><div id="name">Name: <input name="namefield" type="text"/>delete</div></div>
<input id="addnamebtn" type="button" value="Add Name" onclick="addfieldset()"/>
</body>
</html>
I remembered an excellent post from "quirkmodes" briefly explained this. I still hold in my bookmarks. Here it is.
Good Day!