I have some little code that I can't get to work. Here it is:
<input type='password' name='Confirmpwd' id='Confirmpwd'
onkeyup="if(this.value != '') myFunction('checkConfirmpwd', (Password.value == this.value) ? 1 : 0;, this.id);" />
I'm 100% sure that Password.value and this.value are correct when I place them in there. So it's not a problem with the variables.
The problem is that, myFunction isn;t executed anymore when I try to compare Password.value and this.value in the argument like above. myFunction is declared like this:
myFunction(val1, val2, val3) { ...some code... }
What my goal is that I can compare the 2 strings and send them to myFunction when I call the function.
The ; indicates an end of statement. If there are missing parameter or brackets that have not been closed when a semi-colon is encountered, it may result in an error.
This is the case in this instance.
Change the code to something like
if(this.value != '') myFunction('checkConfirmpwd', (Password.value == this.value) ? 1 : 0, this.id);
Put the onkeyup in an external javascript file rather than the same HTML file. It's better to do this for ease-of-editing and performance:
HTML
<input type="password" name="Confirmpwd" id="Confirmpwd" />
JS
document.getElementById("Confirmpwd").onkeyup = function () {
"use strict";
if (this.value !== "") { // !== is better than !=
myFunction("checkConfirmpwd", (Password.value === this.value) ? 1 : 0, this.id); // === is better than ==
}
};
And all we did there was change ;, to ,. It was just a typo
Related
<!--language:lang-html-->
<div class="form-group m-b-40 ">
<input type="text" class="form-control" id="input1">
<span class="bar"></span>
<span class="error_form" id="bname_error_message"></span>
<label for="input1">Regular Input</label>
</div>
In the above html I need to add "form-control-success" class to the input element and keep it true as long as it complies with the state if (pattern.test(bname) && bname !== '')
The same logic should also be applied to the parent element of input. But this time different class "has-success" should be added to the parent class and keep it untill it meets the same condition.
For other cases like else if(bname !== '') and (!pattern.test(bname)) the classes "form-control-success" and "has-success" that has been added to input and its parent respectively should be replaced with their opposite classes "form-control-warning" and "has-warning". This process is bind to "keyup" event. I wonder if there's a method or an elegant way that will reduce the lines of code and keep it simple.
In the clumsy way, the code looks like this:
<!--language: lang-js-->
$("#input1").keyup(function(){
check_bname();
});
function check_bname() {
var pattern = /^[a-zA-Z]*$/;
var bname = $("#input1").val();
if (pattern.test(bname) && bname !== '')
{
$("#bname_error_message").hide();
$("#input1").removeClass("form-control-warning");
$("#input1").parents(".form-group").removeClass("has-warning")
$("#input1").parents(".form-group").addClass("has-success")
$("#input1").addClass("form-control-success");
}
else if(bname === '')
{
$("#bname_error_message").html("Should not be empty");
$("#bname_error_message").show();
$("#input1").removeClass("form-control-success");
$("#input1").parents(".form-group").removeClass("has-success")
$("#input1").addClass("form-control-warning");
$("#input1").parents(".form-group").addClass("has-warning")
}
else
{
$("#bname_error_message").show();
$("#bname_error_message").html("Should contain only Characters");
$("#input1").removeClass("form-control-success");
$("#input1").parents(".form-group").removeClass("has-success")
$("#input1").addClass("form-control-warning");
$("#input1").parents(".form-group").addClass("has-warning")
}
}
here is a version of your code with some more brevity to it and using more dry coding (less repetition), however i havent been able to try the code so it may contain a bug or two, you need to try it before you run, but i hope you get general idea:
<!--language:lang-jquery-->
$elemInput.keyup(function(){
check_bname();
});
function check_bname() {
var pattern = /^[a-zA-Z]*$/,
bname = $elemInput.val(),
$elemInput = $("#input1"),
$elemError = $("#bname_error_message"),
patternMatch = pattern.test(bname) && bname !== '';
$elemError[patternMatch ? 'hide' : 'show']();
$elemError.removeClass(patternMatch ? "form-control-warning" : "form-control-success")
$elemInput.parents(".form-group").removeClass(patternMatch ? "has-warning" : "has-success")
$elemInput.addClass(patternMatch ? "form-control-success" : "form-control-warning");
$elemInput.parents(".form-group").addClass(patternMatch ? "has-success" : "has-warning")
if (!patternMatch) {
$elemError.html(bname === '' ? "Should not be empty" : "Should contain only Characters");
}
}
I think its quite good but I'd suggest some small changes:
Group your else logic in the same block because they are duplicated except the line to set the html text.
Use .parent() instead of .parents(".form-group") to get the input direct parent.
So it could look like this:
$("#input1").keyup(function(){
check_bname();
});
function check_bname() {
var pattern = /^[a-zA-Z]$/;
var bname = $("#input1").val();
if (pattern.test(bname) && bname !== '') {
$("#bname_error_message").hide();
$("#input1").removeClass("form-control-warning");
$("#input1").parent().removeClass("has-warning");
$("#input1").parent().addClass("has-success");
$("#input1").addClass("form-control-success");
} else {
$("#bname_error_message").html(bname === ''? "Should not be empty" : "Should contain only Characters");
$("#input1").removeClass("form-control-success");
$("#input1").parent().removeClass("has-success");
$("#input1").addClass("form-control-warning");
$("#input1").parent().addClass("has-warning");
}
}
$('#input1').on('keyup', function(event) {
check_bname(event.target.value);
});
function check_bname(bname) {
var $bnameInput = $("#input1");
var $bnameErrorMessage = $("#bname_error_message");
var pattern = /^[a-zA-Z]*$/;
if(bname && pattern.test(bname)) {
$("#bname_error_message").hide();
$bnameInput.removeClass("form-control-warning");
$bnameInput.parents(".form-group").removeClass("has-warning");
$bnameInput.addClass("form-control-success");
$bnameInput.parents(".form-group").addClass("has-success");
}
else {
$bnameInput.removeClass("form-control-success");
$bnameInput.parents(".form-group").removeClass("has-success");
$bnameInput.addClass("form-control-warning");
$bnameInput.parents(".form-group").addClass("has-warning");
if (!bname) {
$bnameErrorMessage.text("Should not be empty");
}
else {
$bnameErrorMessage.text("Should contain only Characters");
}
$bnameErrorMessage.show();
}
}
I want to check the value is not blank or one empty space so I wrote a code
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value != " " && OccLocation.value != "") {
alert("not empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass"
/>
You can update your condition as below.
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim() == "") {
alert("empty");
}
If you want to get alert if OccLocation is not empty then :
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim() != "") {
alert("not empty");
}
Your condition is wrong.
You have to use == instead of !=.
If you use && then both condition should be true to return true, which is ultimately impossible at the same time in this case. Use || instead, this will be evaluated as true if any of the condition is true.
The condition should be:
if (OccLocation.value ==" " || OccLocation.value == "")
Even you can simplify the condition by using String.prototype.trim()
:
The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
Try
if (OccLocation.value.trim() == "")
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim()== ""){
alert ("empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass" />
You are checking that it is not empty, then alerting that it is empty. I think you mean to check that it is empty. Change your JS to the following:
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value === " " || OccLocation.value === "")
{
alert ("empty");
}
Your code runs immediately, and the value="" sets it to empty.
Here, I set the value in the markup so it has some, thus it alerts.
var OccLocation = document.getElementById("HdnOccLocation");
console.log(OccLocation.value)
if (OccLocation.value != " " && OccLocation.value != "") {
alert("not empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="dd" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass"
/>
I was playing an online game where you have to find the password by viewing the page source (or inspect element). I am confused my this line if(el.value == ""+CodeCode+""). el.value is my guess, and it says I can continue if my guess is: ""+CodeCode+"". "+CodeCode+" is defined as: "+CodeCode+" == "0xf.at_hackit"; but i tried "0xf.at_hackit" (with and without quotes but it is not working). I have been stuck on this for 2 hours so please help!
Here is the code of the game which has a javascript function:
<!-- :::::::::::::::::==== GAME STARTS HERE ====::::::::::::::::: -->
<h1>Level 10</h1>
<p>Try not to be fooled</p>
<input id="pw" type="password" />
<br/><input type="button" value="OK" onClick="checkPW()"/>
<script type="text/javascript">var CodeCode = "moo6be";
function checkPW()
{
"+CodeCode+" == "0xf.at_hackit";
var el = document.getElementById("pw");
if(el.value == ""+CodeCode+"")
document.location.href="?pw="+el.value;
else alert("Wrong password");
}
</script>
<!-- ::::::::::::::::::==== GAME ENDS HERE ====:::::::::::::::::: -->
The code is assigned right after the <script> tag.
The line "+CodeCode+" == "0xf.at_hackit"; does nothing, its just expression that evaluates to false (comparing two different strings), but no assignment, so no side effects.
<script type="text/javascript">var CodeCode = "moo6be"; // <==== HERE
function checkPW() {
"+CodeCode+" == "0xf.at_hackit"; // <==== this does nothing, its just expression that evaluates to false, but no assignment
var el = document.getElementById("pw");
if(el.value == ""+CodeCode+"") // <==== this is the same as `if(el.value == CodeCode)`
document.location.href="?pw="+el.value;
else alert("Wrong password");
}
</script>
""+CodeCode+"" is the same thing as: "" + CodeCode + ""
CodeCode is assigned right after the tag:
<script type="text/javascript">var CodeCode = "moo6be"; // HERE
function checkPW()
{
"+CodeCode+" == "0xf.at_hackit"; // this does nothing, its just expression that evaluates to false - this is meant to trick you
var el = document.getElementById("pw");
if(el.value == ""+CodeCode+"")
document.location.href="?pw="+el.value;
else alert("Wrong password");
}
</script>
The answer is moo6be.
This is because "+CodeCode+" == "0xf.at_hackit"; has double equals, which just means it is a comparison statement (which will just evaluate to false). It is important to note that this is unrelated to the rest of the program.
The main line here is: if(el.value == ""+CodeCode+"").
Which is: "" (empty string) + CodeCode (moo6be) + "" (empty string).
I am trying to make a simple calculator. You enter one number, you enter the second one, press PLUS and get alert with an answer. I need to show alert('no data') if you click on PLUS when input fields are not touched.
function num1() {
nm = document.getElementById('nsum1').value;
}
function num2() {
mn = document.getElementById('nsum2').value;
}
function plus() {
sum = +nm + +mn;
if (nm == null || mn == null) {
alert('no data');
} else {
alert(sum);
}
}
<input onchange="num1()" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input onchange="num2()" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
So far I have tried if(sum == undefined)/if(sum == null)/if(sum == false)/if(isNaN(sum))/if(sum == "") and nothing seems to work.
If you haven't touched the input field and get the value, then the result would be ""
You need a condition like
if (nm == "" || mn == "") {
alert('no data');
}
And also you should do operation after validations. You are doing operation and then validating.
Fixed other issues aswell.
function plus() {
mn = document.getElementById('nsum2').value;
nm = document.getElementById('nsum1').value;
if (nm == "" || mn == "") {
alert('no data');
} else {
sum = +nm + +mn;
alert(sum);
}
}
<input id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
You can do it much easier
function plus(num1, num2) {
alert(isNaN(num1) || isNaN(num2) ? 'No data' : num1 + num2);
}
function getNumber(id) {
return parseFloat(document.getElementById(id).value);
}
<input id="nsum1" type="number" placeholder="number" maxlength="6" />
<span onclick="plus(getNumber('nsum1'), getNumber('nsum2'))" id="sum">PLUS</span>
<input id="nsum2" type="number" placeholder="number" maxlength="6" />
I've made some changes to your code to make it more robust. See the inline comments for a description.
Declare variables
It is important to declare your variables, when you don't all the variables you are using will wind up in the global scope. When you Google this you will find many articles like this one: https://gist.github.com/hallettj/64478.
Prevent polluting the global scope. In a small website this may not be much of an issue but when working on larger project or with third party code, this is a must. The link above also explains this to some extend.
Use a button If you want something to be interactive, use an HTML element that was meant for it. The button element should be used, it has all sorts of accessibility features the span doesn't have. For instance, by default it will receive focus when navigating your website with the tab key.
Use descriptive variable names nm and mn may mean something to you now but in 6 months it will be a complete mystery. It also makes the code more readable and thus easier to maintain.
Attach event listeners in JS In general it is a bad idea to assign event listeners through the HTML attribute onXXX="". It is more error prone and a lot more time intensive when you want to change something.
// Wrap your code in a closure to prevent poluting the global scope.
(function() {
// Always declare your variables. These variables are no longer scoped to the window object but are no scoped to the function we're in.
var
valueA = null,
valueB = null;
/**
* To check if your input is a valid number requires a couple of checks.
* It is best to place these into their own method so you're other
* method is more readable.
*/
function isNumber(value) {
if (
// == null checks for undefined and null
value == null ||
value === '' ||
isNaN(value)
) {
return false;
}
return true;
}
function onChangeHandler(event) {
var
// Get the element that dispatched the event.
target = event.target;
// Check if the target has the class we've assigned to the inputs, of not you can ignore the event.
if (!target.classList.contains('js-input')) {
return;
}
// Based on the ID of the target, assign the value to one of the variables for the values.
switch(target.id) {
case 'nsum1':
valueA = parseFloat(target.value);
break;
case 'nsum2':
valueB = parseFloat(target.value);
break;
}
}
function onSumTriggerClicked(event) {
// Check if there are numbers to work with
if (
!isNumber(valueA) ||
!isNumber(valueB)
) {
// If not alert the user
alert('no data');
return;
}
sum = valueA + valueB;
alert(sum);
}
function init() {
var
// Get the calculator element.
calculator = document.getElementById('calculator'),
// Get the button to sum up the value.
sumButton = document.getElementById('sum-trigger');
// Add an event listener for the change event.
calculator.addEventListener('change', onChangeHandler);
// Add an event listener for the click event.
sumButton.addEventListener('click', onSumTriggerClicked);
}
// Call the init method.
init();
})();
<div id="calculator">
<input class="js-input" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<button type="button" id="sum-trigger" id="sum">PLUS</button>
<input class="js-input" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
</div>
Try to track it via Inspector, maybe log the values of nm and mn before anything else and correct your condition accordingly(as the sample).
function plus() {
console.log(nm);
sum = +nm + +mn;
if (nm == null || mn == null) {
alert('no data');
}
It will most likely just be blank. So in this case you can modify your condition into:
if (nm === '' || mn === '') {...}
Hope it will help
Please use this as reference.
I've fixed your code.
if ( num1 === '' && num2 === '' ) {
alert('no data');
} else {
alert( parseInt(num1) + parseInt(num2) );
}
I am trying to understand why the following doesn't work:
function SetMaxLength() {
var form = $("body").find("form");
form.each(function () {
var elements = $(this).find("input");
elements.each(function() {
var attr = $(this).attr('data-val-maxlength-max');
if (typeof attr !== typeof undefined && attr !== false) {
$(this).attr('maxlength', attr.value);
}
});
});
}
<form action="/go/somewhere" autocomplete="off" class="form-one" method="post" role="form" novalidate="novalidate">
<input data-val-maxlength="Invalid Email" data-val-maxlength-max="254" type="text" value="">
</form>
when I step through it, it finds 1 form but then on the each part it just skips it, steps over it.
Basically all it is suppose to do it when it sees data-val-maxlength-max attribute, it is suppose to take its value and inject maxlength attribute in the element.
JsFiddle: https://jsfiddle.net/j04vue8r/3/
Since you already have jQuery included in your page, it's better to rewrite your code and make it more "jQuery style".
Here we go:
$('[data-val-maxlength-max]').each(function(){
$(this).attr('maxlength', $(this).data('val-maxlength-max'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/go/somewhere" autocomplete="off" class="form-one" method="post" role="form" novalidate="novalidate">
<input data-val-maxlength="Invalid Email" data-val-maxlength-max="254" type="text" value="">
</form>
I've tried your code and it not step over the each function. The problem is the attr() function that doesn't set the maxlenght attribute because you have a mistake in the code: attr is just the value of data-val-maxlength-max and so you have to write something like this:
$(this).attr('maxlength', attr);
This does what you need:
$(function() {
$("form input").each(function() {
var attr = $(this).attr('data-val-maxlength-max');
if (typeof attr !== undefined && attr !== false) {
$(this).attr('maxlength', attr);
}
});
});
There are two problems with above code.
1. Function SetMaxLength is not called
2. variable attr already contains value. So you don't need to do attr.value
Below code works
function SetMaxLength() {
var form = $("body").find("form");
form.each(function () {
var elements = $(this).find("input");
elements.each(function() {
var attr = $(this).attr('data-val-maxlength-max');
if (typeof attr !== typeof undefined && attr !== false) {
$(this).attr('maxlength', attr);
}
});
});
}
SetMaxLength()
Try this
window.onload = function () {
SetMaxLength();
}
function SetMaxLength() {
var form = $("body").find("form");
form.each(function () {
var elements = $(this).find("input");
elements.each(function() {
var attr = $(this).attr('data-val-maxlength-max');
console.log(attr);
if (typeof attr !== typeof undefined && attr !== false) {
$(this).attr('maxlength', attr);
}
});
});
}
All I did was remove attr.value in your if statement. Works fine for me. You don't need the value, since you already grabbed it in the variable : ). I'd encourage you not to use generic terms like "form" and "elements" and "attr". They might cause issues.
By the way, in the future you may wish to use console.log. It helped me figure out the issue here. I did console.log(attr) right after the var attrline to see what we were getting. In Chrome you can view the console by hitting ctrl + shift + J. Since I saw that it was 254, I knew we didn't need to get a new value : ).