Javascript conditional hiding and showing - javascript

Hello guys I'm confused with javascript code, I want a program that gets the input from the user, and if that input matches a specific value like 1234 I want it to hide part of the form. E.g.
var x=document.getElementById('pin').value;
function hidden() {
if (x.value=1234){
document.getElementById('pin').style.display="none";
}
}
<input type="number" name="pin" placeholder="Please Enter Your Pin" id="pin">
<button onclick="hidden()">Enter</button>

var x=document.getElementById('pin');
function checkPin() {
if (x.value == "1234"){
x.style.display="none";
}
}
<input type="number" name="pin" placeholder="Please Enter Your Pin" id="pin" />
<button onclick="checkPin()">Enter</button>

The value is not a native number, but a string, and you're assigning in the conditional check. Instead of '=' use '==' or '==='.
Try this:
function hidden() {
var x = document.getElementById('pin').value;
if (x === '1234'){
document.getElementById('pin').style.display = 'none';
}
}

Related

using HTML variables with JavaScript

I'm creating a sign up system and tying to make a code using JavaScript that checks the phone number the user is entering and only allows it to be used if it is 10 characters long.
this is my code so far:
JavaScript:
<script type="text/javascript">
function phoneIsValid()
{
var phoneL = document.getElementById("phone").length;
if (phoneL != 10)
{
document.getElementById("phoneErr").innerHTML = "invalid phone number"
return false;
}
else
{
document.getElementById("phoneErr").innerHTML = "";
return true;
}
}
</script>
HTML:
<input type="text" id="phone" name="phone" />
<a id="phoneErr"></a>
the problem is that it always replys that the phone number is not 10 cahracters long, even if it is. what am I doing wrong? I dont know much Javascript and I cant find a solution on the internet.
You don't even need JS for this:
<form>
<input type="text" minlength="10" maxlength="10" required placeholder="Phone number (10 digits)" />
<button>Send</button>
</form>
function phoneIsValid()
{
var phoneL = document.getElementById("phone").value.length;
if (phoneL != 10)
{
document.getElementById("phoneErr").innerHTML = "invalid phone number"
return false;
}
else
{
document.getElementById("phoneErr").innerHTML = "";
return true;
}
}
function checkPhone() {
if(phoneIsValid()) {
alert('Phone number is valid');
} else {
alert('Phone number is NOT valid');
}
}
<input type="text" id="phone" name="phone" />
<a id="phoneErr"></a>
<button type="button" onclick="checkPhone()">Check it</button>
As mentioned in comments - you need to validate value of the textbox, not textbox itself.
It'd be quite simple
HTML: First create a submit button, so that we can detect when the user submits it
<input type="text" id="phone" name="phone" placeholder='Enter Phone number..'/>
<button id='submit'>Submit</button>
JavaScript:
<script type="text/javascript">
document.getElementById('submit').onclick = function(){ // trigger when button is clicked
let phoneL = document.getElementById('phone').value.length; // get the length of the value
if (phoneL >= 10) { //check if the length is 10 characters or more
alert('Valid phone number!')
} else {
alert('Invalid phone number!')
}
}
</script>
If you need any other help, feel free to let me know
Try getting the length of the "value".
var phoneL = document.getElementById("phone").value.length;
˄

Avoid enter dot in input field

I have an input field which is of number type, when I enter the dot I am not getting the value. So what I am trying to achieve is the I don't want the user to enter dot on the input field
function handleChange (value) {
console.log(value)
}
<input type="number" onchange="handleChange(this.value)"/>
on each number entering I am getting the value, but when I type dot (.), I am not getting how can I block this when user type it
<input name="num" type="number" min="1" step="1" onkeypress="return event.charCode >= 48 && event.charCode <= 57">
referance from this url
https://stackoverflow.com/a/44379790/4316212
Add This oninput="this.value = this.value.replace(/[^0-9]/, '')"
function handleChange (value) {
console.log(value)
}
<input type="number" onchange="handleChange(this.value)" oninput="this.value = this.value.replace(/[^0-9]/, '')"/>
if you want to block '.' you can use this way,
function handleChange (value) {
console.log(value)
}
var inputBox = document.getElementById("inputBox");
var invalidChars = [
".",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" onchange="handleChange(this.value)/>
It is generally not a good idea to use inline event handlers.
For more control you should check/use the atributes of a number input.
If you want to completely control the input, use a readonly field and handle it using your own handler. Here's a snippet using event delegation. It uses the step attribute from the number input field for adding/subtracting.
document.addEventListener('click', handle);
function handle(evt) {
if (evt.target.dataset.numinput) {
const inp = document.querySelector(`#num`)
inp.value = ( +inp.value + +(`${evt.target.dataset.numinput}${inp.step}`) )
.toFixed(2);
}
}
<input id="num" type="number" step="0.1" readonly/>
<button data-numinput="-"> - </button>
<button data-numinput="+"> + </button>

User must enter a value if a checkbox is checked

I have the following input field and a checkbox:-
<input id="ClientManagerApproval_e565da24-d454-4537-b902-771a37689e9d_MultiChoiceOption_0" type="checkbox">
<input type="text" value="" id="ProjectManHoursUsed_becead30-410d-42de-872e-c12ad4c322b2_$NumberField" title="Man Hours Used" size="11" class="ms-input" style="ime-mode : inactive">
now what i am trying to do inside jQuery, if that if the checkbox is checked then the user must enter a value inside the input field, i tried this but it did not work (the alert will never show!)
if ($("[id^=ProjectManHoursUsed_]").value === "" && $("[id^=ClientManagerApproval_]").is(':checked'))
{
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
JQuery has its own function for getting values. Replace
$("[id^=ProjectManHoursUsed_]").value
by
$("[id^=ProjectManHoursUsed_]").val()
See here:
$("button").on("click", function(){
if ($("[id^=ProjectManHoursUsed_]").val() === "" && $("[id^=ClientManagerApproval_]").is(':checked')){
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="ClientManagerApproval_e565da24-d454-4537-b902-771a37689e9d_MultiChoiceOption_0" type="checkbox">
<input type="text" value="" id="ProjectManHoursUsed_becead30-410d-42de-872e-c12ad4c322b2_$NumberField" title="Man Hours Used" size="11" class="ms-input" style="ime-mode : inactive">
<button>submit</button>
You can achieve the result you're looking by using the following code snippet without needing any jQuery at all:
if (document.querySelector('.chkbx').checked) { // I'd recommend using class instead of id, here chkbx if the class attr of the checkbox input -> class="chkbx"
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
You are trying to check if value is empty when value is undefined. If you want to make sure if there's any value, you can use ! operator. You should use === to make sure for empty string over null.
I just changed your code from $("[id^=ProjectManHoursUsed_]").value === "" to !$("[id^=ProjectManHoursUsed_]").value and it's working fine.
function testMe() {
let result = true
if (!$("[id^=ProjectManHoursUsed_]").val() && $("[id^=ClientManagerApproval_]").is(':checked'))
{
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
return result
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onSubmit="return testMe();">
<input id="ClientManagerApproval_e565da24-d454-4537-b902-771a37689e9d_MultiChoiceOption_0" type="checkbox"/>
<input type="text" value="" id="ProjectManHoursUsed_becead30-410d-42de-872e-c12ad4c322b2_$NumberField" title="Man Hours Used" size="11" class="ms-input" style="ime-mode : inactive"/>
<input type='submit' value="Click"/>
</form>

Input type validations are not working for the very first time after page loads

I have a text box, in that I wants to allow only alphabets.
Below is my code :
state ={
NomName: '',
}
onlyAlpha(e) {
var regex = /^[a-zA-Z ]*$/;
if(e.target.value === '' || regex.test(e.target.value)) {
this.setState({NomName:e.target.value})
}
}
render = () => {
return (
<label for="nominee">Nominee name</label>
<input type="text" value={this.state.NomName} id="nominee" class="form-control"
onChange={this.onlyAlpha.bind(this)} autoComplete="off"
maxLength="100"/>
)}
The input validations are not working (I am able to enter Numbers) at very first time after page loads. But once you cleared the field and try to re-enter the value it won't takes numbers (It works).
How can I make it run at each and every time.?
Please let me know if I am doing anything wrong.
I suggest you start using fat arrow functions. Make the onlyAlpha function like so:
onlyAlpha = (e) => {
var regex = /^[a-zA-Z ]*$/;
if(e.target.value === '' || regex.test(e.target.value)) {
this.setState({NomName:e.target.value})
}
}
This would remove the usage of this.onlyAlpha.bind(this).
Also, I think you should pass the function to the onChange listener like so:
<input type="text" value={this.state.NomName} id="nominee" class="form-control"
onChange={this.onlyAlpha} autoComplete="off"
maxLength="100"/>

I want to restrict users from entering number ending with 5

Here is text field.I want users to only enter value like 210,220,230,... and restrict from entering something like 215,225,...
I am looking for suggetions.I don't have much knowledge of javascript.
If you just want to prevent strings that end in '5':
document.getElementById("input").onblur = checkEND;
function checkEND() {
let firstValue = event.currentTarget.value;
if(firstValue.endsWith('5')){
warnUser()
}
}
This won't validate that the string is a valid number though.
function testInput() {
var key = window.event.keyCode;
var x = document.getElementById('textarea').value
var y = document.getElementById('textarea2').value
var z = parseInt(x, 10);
if (z+10 == y) {
document.getElementById('result').innerHTML = "valid";
} else {
document.getElementById('result').innerHTML = "invalid";
}
}
<textarea maxlength="3" id="textarea">5</textarea>
<textarea maxlength="3" id="textarea2">15</textarea>
<button onclick="testInput()">Test Input</button>
<div id="result"></div>
The first input is your first number, the second is your second number.
See Comments If Your Wondering Why This Doesn't Answer His OG Question
You can experiment with the setCustomValidity() of input elements (https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) from an onblur, onchange or oninput handler. If you are not satisfied with the value, set an error message, and an empty string otherwise. As long as the error message is set to non-empty, it is displayed and the form refuses to submit:
function check5() {
cgiftcardq.setCustomValidity(cgiftcardq.value.endsWith('5')?"Nope, it can not end with 5":"");
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" onblur="check5()">
<input type="submit" value="Send">
</form>
(StackOverflow snippets interfere with form submission - probably as part of security -, so successful submission just makes the form disappear)
As setCustomValidity() does not work everywhere (according to the compatibility table, it will not work on non-Andorid mobiles), classic "budget" solution may be mentioned too: you can simply disable the send button as long as you are not satisfied with the input:
function check5() {
if(cgiftcardq.value.endsWith('5')){
send.disabled=true;
message.innerHTML="Nope, it can not end with 5";
} else {
send.disabled=false;
message.innerHTML="OK";
}
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" oninput="check5()">
<input id="send" type="submit" value="Send" disabled>
</form>
<div id="message"></div>

Categories

Resources