User must enter a value if a checkbox is checked - javascript

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>

Related

Compare input text with person name belongs to only one input number id

Im trying to write a validation for 2 groups of fields. I have 6 inputs, 3 for text name and 3 more for id number... the validation should do this "if input name="RE_SignedByID" has an input type name="RE_SignedByName", then other inputs name="RE_SignedByID", should NOT contain the same name="RE_SignedByName" More easy explanation... one ID number should have only one Person Name (Id number is unique for one person name). What can I use for that? Should I map() all the inputs?
Those are my inputs:
<div id="signedBy" class="clearfix">
<label>Signer, person ID & name</label>
<span id="signedByID" class="ids half">
<input type="text" name="RE_SignedByID" placeholder="personID, person1" data-validate="" tabindex="101" required>
<input type="text" name="RE_SignedByID" placeholder="personID, person2" data-validate="" tabindex="103">
<input type="text" name="RE_SignedByID" placeholder="personID, person3" data-validate="" tabindex="105">
</span>
<span class="names half">
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" required>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="104">
<input type="text" name="RE_SignedByName" placeholder="name, person3" tabindex="106">
</span>
</div>
I guess it should also be an "on change" function? or can I make the validation on click? Some ideas...? Im actually compleatley lost here...
Thanks in advance!!!
Maybe use different class names for all 3 of them to make them unique?
<input class="name1">
<input class="name2">
<input class="name3">
I'm not sure what you mean but if you want to make the input types unique and not call them all when you write class="names half", then you should give them all unique class names.
So from my understanding you don't want multiple fields to have the same value.
My approach would be this:
let inputTimeout = null; //set an empty timeout object
let vars = [null, null, null, null]; // create an array containing as many nulls as you have inputs
$('.nameInput').on('keyup', function(){
let self = $(this);
clearTimeout(inputTimeout); //clear the timeout
inputTimeout = setTimeout(function(){ //set a timeout to check whether there is a dupe after the user has stopped typing
if (vars.indexOf(self.val()) == -1){ //check if the vals array contains the newly entered string
vars[self.attr('data-inputnum')] = self.val(); //insert the value into the array
}else{
//handle duplicates here
}
}, 500); //500ms is a sensible value for end of user input, change it if users complain that your app is too fast/slow
});
You then just have to edit your HTML a bit so that all name inputs have a class in common (i used .nameInput) and have a data-inputnum attr.
This would look something like this:
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" class='nameInput' data-whichinput='0'/>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="103" class='nameInput' data-whichinput='1'/>
<!--and so on-->
Of course, never rely on JavaScript verification alone, always also check inside your backend. However this would be out of scope for this answer.
Hi Thanks all for the help, made me realize a couple of things till I got the answer. This is my working code:
var valSignedID = $("[name=SignedByID]").map(function() {
return this.value.trim();
}).get();
var valOwnersID = $("[name=OwnersID]").map(function() {
return this.value.trim();
}).get();
valSignedID.sort();
valOwnersID.sort();
for (var i = 0; i < valSignedID.length - 1; i++) {
if (valSignedID[i] == valSignedID[i + 1] && valSignedID[i] != "") {
alert(" You can not have duplicated signers ID's");
return false;
// break;
}
}
for (var i = 0; i < valSingedName.length; i++) {
if (valSingedName[i] == valSingedName[i + 1] && valSingedName[i] != "") {
alert(valSingedName[i] + " should not have different ID");
//return false;
}
}

Javascript conditional hiding and showing

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

Insert missing letter javascript game

I'm making a language learning game with javascript. I want the user to be able to write the missing letter and the results to be validated through javascript if they are right or wrong.
<form>
De<input id="letterone" type="text" name="latter" pattern="[A-Za-z]{1}">
ign<input id="lettertwo" type="text" name="latter" pattern="[A-Za-z]{1}">r
<input type="submit">
</form>
My javascript code.
if ((getElementById('letterone')==='s') && (getElementById('lettertwo')==='e')) {
alert('Correct');
}else{
alert('Wrong');
}
There are number of errors on your code :
No 'document' before getElementById
No 'value' after the object
No click handler
Incorrect id while accessing the object
Using input type=submit causes an unwanted page refresh as Useless Code comments below.
document.getElementById('submit').addEventListener('click', function() {
if ((document.getElementById('latterone').value==='s') && (document.getElementById('lattertwo').value==='e')) {
alert('Correct');
}else{
alert('Wrong');
}
});
<form>
De<input type="text" id="latterone" pattern="[A-Za-z]{1}">
ign<input type="text" id="lattertwo" pattern="[A-Za-z]{1}">r
<input type="button" id="submit" value="Submit">
</form>
var lOne = document.getElementById('letterone').value; // get the value of the first input
var lTwo = document.getElementById('lettertwo').value; // get the value of the second
if (lOne === 's') && lTwo === 'e') {
alert('Correct');
}else{
alert('Wrong');
}

How to validate a simple web form

Im working on a small form and using js to validate if the fields are empty or not. I have a span class next to the name field "name" "email".
For the "name" field, i have a span class called "error".
For the "email" field, i have another span class called "error2".
what can i do to only use one class to display the "error message", because of course i will have more field and I don't want to keep adding more classes. error3, error4
HTML:
<form action="#i" name="myForm" onsubmit="return(validate());">
Name: <span id="error"></span><br>
<input type="text" name="Name" /><br><br>
EMail: <span id="error2"></span><br>
<input type="text" name="EMail" /><br> <br>
<input type="submit" value="Submit" /> <br>
</form>
JS:
function validate()
{
var t = 0;
if( document.myForm.Name.value == "" )
{
document.getElementById('error').innerHTML = "<br>Empty";
t = 1;
}
if( document.myForm.EMail.value == "" )
{
document.getElementById('error2').innerHTML = "<br>Empty";
t = 1;
}
if(t == 1)
{
return false;
}
else
return true;
}
Instead of giving the spans the attribute of Id, use classes instead. So for example, you can define ALL your spans as follows:
<span class="error"> ... </span>
Then, in your validate function, you can obtain these spans through:
document.getElementsByClassName('error');
Keep in mind though, this returns an array, which would actually be perfect for your function. This way, you can write a basic for-loop to go through each span and make sure each field is filled in correctly.

How to manipulate individual input field values without a lot of code

I wrote some code using jQuery to convert <input> field values from one unit system to another (English <-> Metric). All was going well until I have realized that I am using a class selector, so instead of each value doing its conversion individually, all values (with same class) get converted to the same identical value (equal to the first occurrence of class).
An obvious solution is to assign an id to each value, which I suppose will work, but I am here to ask if there is a better way. I have a lot of values (which is why I tried using class), and would like to avoid using id, if possible. But, all I am looking for is "convert each value individually (using my conversion function)". How can this be done?
jQuery
function convertValues() {
if ($('#unit_system').val() == "English") //if changed to English
{
$('.value_gpm').val( //do converstion from Metric to English
convert($('.value_gpm').val(), "m3h", "gpm")
);
}
else if ($('#unit_system').val() == "Metric") //if changed to Metric
{
$('.value_gpm').val( //do conversion from English to Metric
convert($('.value_gpm').val(), "gpm", "m3h")
);
}
}
Calling Function
//below code is for select box (HTML for it is not shown)
$("#unit_system").change(function(){ //select box change detected
convertValues(); //function is called
});
HTML at first (before Select box change)
<input type="text" class="value_gpm" name="design_a" value="444" />
<input type="text" class="value_gpm" name="design_b" value="555" />
<input type="text" class="value_gpm" name="design_c" value="666" />
<input type="text" class="value_gpm" name="design_d" value="777" />
<input type="text" class="value_gpm" name="design_e" value="888" />
HTML after (after Select box is changed)
<input type="text" class="value_gpm" name="design_a" value="1954.87" />
<input type="text" class="value_gpm" name="design_b" value="1954.87" />
<input type="text" class="value_gpm" name="design_c" value="1954.87" />
<input type="text" class="value_gpm" name="design_d" value="1954.87" />
<input type="text" class="value_gpm" name="design_e" value="1954.87" />
Expected behavior: conversion produces different value per row
Actual behavior: same value produced for each row
Just loop through them, something like this.
var inputs = $('.value_gpm');
for(i=0;i < inputs.length; i++){
var input = inputs[i];
input.val( convert(input.val(), "m3h", "gpm") );
}
Best bet - using $.each and $(this).
$(document).ready(function(){
var valueEls = $('.value_gpm');
$("#unit_system").change(function(){
var unit = $(this).val();
switch(unit){
case "English":
valueEls.each(function(){
$(this).val(convert($(this).val(), "m3h", "gpm");
});
break;
case "Metric":
valueEls.each(function(){
$(this).val(convert($(this).val(), "gpm", "m3h");
});
break;
}
});
});
Use each()
$("value_gpm").each(function () {
convert(this.val(), ...etc
The less lines of codes I figure out for this is this:
var unit_system = $('#unit_system').val();
$('.value_gpm').each(function(){
convert($(this).val(), unit_system == "English" ? "m3h" : "gpm", unit_system == "English" ? "gpm" : "m3h");
});
You can use jQuery each:
$("#unit_system").change(function(){
var fromUnit = "m3h";
var toUnit = "gpm";
if ($(this).val() == "Metric"){
fromUnit = "gpm";
toUnit = "m3h";
}
$('.value_gpm').each(function(){
$(this).val(convert($(this).val(), fromUnit, toUnit));
});
});

Categories

Resources