How to stop an event happening in Javascript - javascript

On this simple to-do list how do i stop the program from still creating a new paragraph when there is nothing in the text field. When Add To List is blank, i want the function to only output the alert, nothing else. I've tried many things but nothing has worked. Any help is greatly appreciated. Thanks!
JS Fiddle = http://jsfiddle.net/Renay/g79ssyqv/20/
<p id="addTask"> <b><u> To-Do List </u> </b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
function addText(){
var input = document.getElementById('inputTask').value;
var node=document.createElement("p");
var textnode=document.createTextNode(input)
node.appendChild(textnode);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
removeTask.addEventListener('click', function() {
node.parentNode.removeChild(node);
}, false)
node.appendChild(removeTask);
if (input == "") {
alert('Please add an entry');
}
}

Move your if statement to the top, just after your input variable is assigned to, and add a return to it to break out of the function:
function addText() {
var input = ...;
if (input == "") {
alert("...");
return;
}
var node ...;
...
}
Amended JSFiddle demo.
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead. (MDN)

You could just move the "creation" section in your else block
var input = document.getElementById('inputTask').value;
if (input == "") {
alert('Please add an entry');
} else {
var node=document.createElement("p");
var textnode=document.createTextNode(input)
node.appendChild(textnode);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
removeTask.addEventListener('click', function() {
node.parentNode.removeChild(node);
}, false)
node.appendChild(removeTask);
}

Related

How to select two input fields at once and check if they are filled?

So I am making a game and I need to check if these two HTML <input> fields have some data before I do an alert(); saying that they won. Unfortunately, I don't know how to implement this and I have been stuck at it for hours, please do help, attaching a screenshot for assistance.
In the image, I want to constantly monitor the 2 empty <input> fields and once there is data IN BOTH, then I want to throw up an alert();
Here's what I tried:
var firstLetterField = document.querySelectorAll("input")[0].value.length;
var secondLetterField = document.querySelectorAll("input")[1].value.length;
if (!firstLetterField && !secondLetterField) {
console.log("Please ignore this message: NOT_FILLED...");
} else {
alert("That's right! The word was " + spellingOfWord.join("").toUpperCase() + "! Thanks for playing!");
window.location.href = "/";
}
How about just adding a common class to your user input and use querySelectorAll to perform your check ?
eg
<html>
<body id="game">
<input data-expected="m" class="user-input" />
<input data-expected="a" class="user-input" />
<div id="keyboard">
<button>d</button>
<button>c</button>
<button>b</button>
<button>a</button>
<button>d</button>
<button>m</button>
<button>e</button>
</div>
</body>
<script>
const inputs = document.querySelectorAll(".user-input");
const keyboard = document
.querySelector("#keyboard")
.querySelectorAll("button");
let inputPosition = 0;
function nextInput() {
inputPosition += 1;
if (inputPosition === inputs.length) {
alert("you won");
}
}
function handleClick(event) {
const input = inputs.item(inputPosition);
const submittedValue = event.target.innerHTML;
if (input.dataset.expected === submittedValue) {
input.value = submittedValue;
setTimeout(nextInput);
}
}
keyboard.forEach((button) => button.addEventListener("click", handleClick));
</script>
</html>
You could register an event-listener and check if your condition is met:
var firstLetterField = document.querySelectorAll("input")[0];
var secondLetterField = document.querySelectorAll("input")[1];
// Function to call when both inputs contain values
function bothReady() {
console.log("bothReady", firstLetterField.value, secondLetterField.value);
}
document.addEventListener("keyup", function (e) {
// Wait for both fields to have values
if (firstLetterField.value.length > 0 && secondLetterField.value.length > 0) {
bothReady();
}
});
Your code just works fine. There were just some mistakes that I noticed.
You tried to use the length to detect if it is empty. You could instead compare it with an empty string.
You reversed the boolean value using else. It looks that does the opposite of what you want.
In the code you showed you didn't actually defined spellingOfWord. So I did it for you.
The location "/" is not compatible in every server. So I would recomment replacing it by "index.html".
Here is the code that I just created
function input_inputEvent() {
var firstLetterField = document.querySelectorAll("input")[0].value;
var secondLetterField = document.querySelectorAll("input")[1].value;
var thirdLetterField = document.querySelectorAll("input")[2].value;
if (firstLetterField.length != "" && secondLetterField != "") {
alert(
"That's right! The word was " +
[firstLetterField,secondLetterField,thirdLetterField].join("").toUpperCase() +
"! Thanks for playing!"
);
window.location.href = "index.html";
}
}

Remove a specific word from a div in jquery

checked input
<input id="add_stop" name="attach_img" type="checkbox" class="required custom-control-input">
Here is my div
<div class="emojionearea-editor">
Hello World. STOP to opt out
</div>
I want to remove just STOP to opt out if it exists in the inner HTML of div.
here is my jquery code
$('#add_stop').change(function (event) {
if ($(this).is(':checked')) {
if ($('.emojionearea-editor').html().indexOf("STOP to opt out") != -1) {
} else {
$('.emojionearea-editor').append('STOP to opt out ');
}
} else {
var name = $('.emojionearea-editor').html();
/* remove code should be here.... */
alert(name);
}
});
Here I want to add when checked. I append the text when it not exist. Now I want to remove text if it exists. Now my question is How can I remove the existing text from inner Html??
Is this what you are looking for?
$('#add_stop').change(function (event) {
var keyword = 'STOP to opt out';
if ($(this).is(':checked')) {
if ($('.emojionearea-editor').html().indexOf(keyword) != -1) {
} else {
$('.emojionearea-editor').append(keyword);
}
} else {
var name = $('.emojionearea-editor').text().replace(keyword,"");
alert(name);
}
});
I've made the words you want to replace into a variable. That way when you chance the text in the variable it will apply to every place where it's used.
Please note that you should use .text() and not .html() since the .html() will include all html code in that object.
Demo
$('#add_stop').change(function (event) {
var keyword = 'STOP to opt out';
if ($(this).is(':checked')) {
if ($('.emojionearea-editor').html().indexOf(keyword) != -1) {
} else {
$('.emojionearea-editor').append(keyword);
}
} else {
var name = $('.emojionearea-editor').text().replace(keyword,"");
alert(name);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="add_stop" name="attach_img" type="checkbox" class="required custom-control-input">
<div class="emojionearea-editor">
Hello World. STOP to opt out
</div>
html() function takes one parameter to set inner Html of the DOM.
So like this:
var text = $('.emojionearea-editor').html();
text = text.replace("STOP to opt out", "");
$('.emojionearea-editor').html(text);
var name = $('.emojionearea-editor').html().replace("STOP to opt out", "");
$('.emojionearea-editor').html(name)
I changed your JQuery code a bit
$("#add_stop").change(function() {
if(this.checked){
if(!$(".emojionearea-editor").html().includes("STOP to opt out ")){
$(".emojionearea-editor").append("STOP to opt out ")
}
}else{
var name = $('.emojionearea-editor').text();
$('.emojionearea-editor').text(name.replace("STOP to opt out ", ""))
alert(name);
}
})
This should allow you to add and remove the "STOP to opt out"
Here's a codepen with it working

loop through all fields and return false if validation of any one field fails jquery

I am facing big trouble resetting the flag variables. I am not sure where I am missing :(
I have a form with lots of text fields. I am trying to loop through all the fields and on blur of each of the field I am doing some validations. If any of the validation for any of the field fails it should not submit the form. But now I am having a big trouble doing this. If I have 3 fields and the first value I have entered wrong and next two fields if I have given correct, its submitting the form which should not be. Can somebody please help me in this?
var globalValid = false;
var validators = {
spacevalidation: function(val) {
if($.trim(val) != "")
return true;
else
return false;
},
//Other validation fns
};
$('#form1 .required').blur(function(){
var input = $(this);
var tmpValid = true;
input.each(function(){
var classReturn = true;
validatorFlag = true;
input.next('ul.innererrormessages').remove();
input.removeClass('required_IE');
if(firstTime)
{
input.addClass('valid');
}
if (!input.val()) {
input.removeClass('valid');
input.addClass('required');
var $msg = $(this).attr('title');
input.after('<ul class="innererrormessages"><li>'+$msg+'</li></ul>');
globalValid = false;
}
else{
if(this.className) {
var classes = this.className.split(/\s+/);
for(var p in classes) {
if(classes[p] in validators) {
tmpValid = (tmpValid && validators[classes[p]] (input.val())) ? tmpValid : false;
}
}
}
if(tmpValid == false){
input.removeClass('valid');
input.addClass('required');
var $msg = input.attr('title');
input.after('<ul class="innererrormessages"><li>'+$msg+'</li></ul>');
}
}
});
globalValid = tmpValid;
});
$('#form1').submit(function() {
var returnValue = true;
if(globalValid )
{
returnValue = true;
}
else{
returnValue = false;
}
alert("returnValue "+returnValue);
return returnValue;
});
Using this code, if I put a wrong value for first field and correct value for the other two fields, ideally it should return false. But its returning true. I think I am not properly resetting the flag properly
Checkout this example which provides the basic premise of what needs to occur. Each time the blur event is fired you must validate all three fields and store the result of their validation to a global variable.
HTML
<form>
<input />
<input />
<input />
<button type="submit">Submit</form>
</form>
Javascript
var globalValid = false; //Global validation flag
$("input").blur(function(){
//local validation flag
var tmpValid = true;
//When one input blurs validate all of them
$("input").each(function(){
//notice this conditional will shortcircuit if tmpValid is false
//this retains the state of the last validation check
//really simple validation here, required value less than 10
tmpValid = (tmpValid && this.value && this.value < 10) ? tmpValid:false;
});
//assign the result of validating all inputs to a global
globalValid = tmpValid;
});
$("form").submit(function(e){
//This is just here to make the fiddle work better
e.preventDefault();
//check the global validation flag when submitting
if(globalValid){
alert("submitted");
}else{
alert("submit prevented");
}
});
JS Fiddle: http://jsfiddle.net/uC3mW/1/
Hopefully you can apply the principles in this example to your code. The main difference is the code you have provided does not validate each input on blur.

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

Input text form, using javascript to clear and restore form contents problem

I have this line of HTML
<input type="text" name="addQty" size="1"
class="addQty" value="0"
onclick="$(this).val('')"
onblur="itmQtyChk($(this).val())" />
the itmQtyChk function does this:
function itmQtyChk( qty ) {
if( qty == "") {
$(this).val("0");
} else {
$(this).val(qty);
}
}
My problem is I want it to return the original value to the input text if they exit the field and don't change anything, but it is not working.
Thank you for any help.
this in itmQtyChk function is not referring to the input but to the window object.
Change the function to accept the input as parameter:
function itmQtyChk(input) {
if (input.val() == "") {
input.val("0");
}
// the else part is not needed
}
with the onblur event also:
onblur="itmQtyChk($(this))"
Check this fiddle, it has lots of room for improvement, but it can help you:
http://jsfiddle.net/eDuKr/1/
$(function(){
var cacheQty;
$('.addQty').click(function(){
cacheQty = $(this).val();
$(this).val('');
}).blur(function(){
if ($(this).val() === ''){
$(this).val(cacheQty);
}else{
cacheQty = $(this).val();
}
});
});

Categories

Resources