If value is empty - javascript

I have some code that saves the users input into local storage and then prints the value into the selected ID.
function saveData() {
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.value);
console.log(localStorage.getItem("server"));
document.getElementById("yourname").innerHTML ="Okay " + (localStorage.getItem("server")) + " Let's get started! Push the button on the right to begin the story!" ;
}
How do I make it so if the input field is empty a statement is produced informing the user to input their name.
I've had a look at if and else statements but anything I try doesn't seem to work.
Edit:
Figured it out!
if (saveServer.value == "") {
document.getElementById("yourname").innerHTML = "Please input your name";
}
else {
document.getElementById("yourname").innerHTML ="Okay " + (localStorage.getItem("server")) + " Let's get started! Push the button on the right to begin the story!" ;
}

Add a condition to check if input not empty.
function saveData() {
var input = document.getElementById("saveServer").value;
if(input ==="") alert("Enter saveServer");
else{
localStorage.setItem("server", input.value);
console.log(localStorage.getItem("server"));
document.getElementById("yourname").innerHTML ="Okay " + (localStorage.getItem("server")) + " Let's get started! Push the button on the right to begin the story!" ;
}
}

Like this:
function saveData() {
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.value);
var serverValue = localStorage.getItem("server");
if (!serverValue) {
document.getElementById("error").innerHTML = "Oh dear! Nothing was found";
}
document.getElementById("yourname").innerHTML = "Okay " + (localStorage.getItem("server")) + " Let's get started! Push the button on the right to begin the story!";
}
Fiddle: http://jsfiddle.net/KyleMuir/LhyXr/

Related

My validation and the push() is not working

The user has to type the information in a text box and then click on the button to add the names. If the format is correct the name will appear below the text box. If the format is incorrect a message will be generated that reads "Incorrect Format".
The users inputs will create a list of names that will appear underneath the text box.
function validate(name){
var str = [];
var name = document.getElementById("letters");
var check = /^[A-Za-z]+$/;
if(name.value.match(check)){
str.push(document.getElementById("letters"));
document.write("Name: " + name);
}
else{
document.write("Incorrect Format");
}
}
validate();
I think this is what you're trying to achieve:
function validate() {
console.clear();
var check = /^[A-Za-z]+$/;
var inputVal = document.getElementById('letters').value;
if (inputVal.match(check)) {
console.log("Name: " + inputVal);
document.getElementById('container').innerHTML += inputVal + "<br/>";
} else {
console.log("Incorrect Format");
}
}
document.getElementById('btnValidate').addEventListener('click', validate);
<input type="text" id="letters" />
<input type="button" id="btnValidate" value="Validate" />
<div id="container"></div>

How to end a function if prompt answer is no in JavaScript?

I wrote this function for a plug.dj script, it adds a chat message if the answer is yes, but I'm having trouble to end the function if the answer is no. I am not a pro programmer.
Code:
f_votelggr: function (obj){
if (nScript.mehShow) {
if (obj.vote != 1) {
prompt(obj.user.username + " didn't liked this song! Do you want to alert the users?")
if ("yes");
API.sendChat(obj.user.username + "didn't like this song!");
} else {
return
};
},
Try this:
if ("no"){
return null;
}
I guess this is what you are looking for. It will leave the function.
Edit:
var input = prompt(obj.user.username + " didn't liked this song! Do you want
to alert the users?")
if (input == "yes"){
API.sendChat(obj.user.username + "didn't like this song!");
}
else if{
(input == "no"){
// do stuff here
return null;
} else {
return}
};
You should receive the prompted input from user
var input = prompt(obj.user.username + " didn't liked this song! Do you want
to alert the users?")
if (input == "yes"){
API.sendChat(obj.user.username + "didn't like this song!");
}
else{
return;
};
And also you have
if ("yes");
Which terminates your if there right away. Remove that ; and use {} just to avoid confusion and bugs.
var input = prompt(obj.user.username + " didn't liked this song! Do you want to alert the users?");
input = input.toLowercase();
if (input === "yes") {
API.sendChat(obj.user.username + "didn't like this song!");
} else {
return false;
};

Editing the name and check for duplicates

I am trying to edit an option of a dropdown and check if the newly edited option is already present in the dropdown.
If it is, it should give an alert, else edit and add the new option in the dropdown.
But there is a case when user clicks edit but then doesn't want to change the name and clicks OK (as that option is in the dropdown it gives alert that the option is already present).
How to check this excluding the option which I am editing?
function IsNameAlreadyPresent(DropdownID,Name){
var Result = false;
$.each($("#"+DropdownID+" option"),function(i,e){
if(e.innerHTML == Name){
Result = true;
return false;
}
});
return Result;
}
function EditOptionName() {
var Name = $("#txtName").val();
if(IsNameAlreadyPresent('DropdownId',Name)) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
}
else{
$('#DropdownId').find(':selected').text($('#txtName').val());
}
}
You want to check first that the user has actually edited the value or selected the previous value only. Store this in a flag variable say 'modified'. Then use the below code:
function EditOptionName() {
var Name = $("#txtName").val();
var modified;
if(IsNameAlreadyPresent('DropdownId',Name) && modified) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
}
else{
$('#DropdownId').find(':selected').text($('#txtName').val());
}
}

Check if placeholder text already exists within a string

I have an #error paragraph. Everytime there is an error within the form on submit. The inputs placeholder text gets added to the #error paragraph.
My problem:
It happens everytime a user clicks submit. So the #error message returns:
Please fill in yourfirst name, last name, company, position, first
name, last name, company, position, first name, last name, company,
position, first name, last name, company, position, first name, last
name, company, position, first name, last name, company, position,
I've looked for other solutions and tried this:
if (input.attr('placeholder').indexOf($('#error')) >= 0){
} else{
$('#error').append(input.attr('placeholder').toLowerCase() + ', ');
}
Is there any way to check if the placeholder text already exists in the #error message? Here's a fiddle. I'm sorry it's so convoluted. But its what i've been working on and had it handy.
Thanks for your help in advance!
http://jsfiddle.net/8YgNT/20/
var errorText = '';
//Validate required fields
for (i = 0; i < required.length; i++) {
var input = $('#' + required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("tobefixed");
errornotice.fadeIn(750);
if (input.attr('placeholder').indexOf($('#error')) >= 0) {
// do nothing
} else {
errorText = errorText + $(input).attr('placeholder').toLowerCase() + ', ';
}
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("tobefixed");
}
}
$('#error').html('').append('Please fill in your ' + errorText);
I simple add one line in your fiddle and it's working now:
required = ["id_first_name", "id_last_name", "id_firmbox", "id_job_title"];
errornotice = $("#error");
emptyerror = "Please fill out this field.";
$("#startform").submit(function(){
//Validate required fields
$("#error").html("Please fill in your");
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("tobefixed");
errornotice.fadeIn(750);
// =====Here===== //
if (input.attr('placeholder').indexOf($('#error')) >= 0){
} else{
$('#error').append(input.attr('placeholder').toLowerCase() + ', ');
}
// ============== //
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("tobefixed");
}
}
if ($(":input").hasClass("tobefixed")) {
return false;
} else {
errornotice.hide();
return true;
}
});
$(":input").focus(function(){
if ($(this).hasClass("tobefixed") ) {
$(this).val("");
$(this).removeClass("tobefixed");
}
});
This line do the all trick:
$("#error").html("Please fill in your");
Saludos ;)
If you want to check whether #error contains the string you're wondering about, you can use
($('#error').text().indexOf(a_string)) != -1
This will return true if #error contains a_string.
There's a longer discussion on searching strings for other strings in this question.
It seems you're doing it the wrong way round (and forgetting to get the text out of the #error element):
if ( $('#error').text().indexOf( input.attr('placeholder') ) >= 0)

How do I add dynamic content to a div generated dynamically?

Basically I am validating a form, I am collecting the error messages and I am appending them to a div generated dynamiclly. Now I am unable to append these message to this div .here is what I had done
//generates a div onclick of submit button
$("body").append("<div class='overlay'><div class='errorContainer'>.html(errorMsg)</div><div>`<a href='javascript:void(0);' class='cross'>X</a><div></div>");
.html(errorMsg) this causes error/is incorrect
function closeErrorBox() {
var errorMsg = "";
var ferrorMsg = "Please say your first name" + "<br>";
var aerrorMsg = "Please type address" + "<br>";
var eerrorMsg = "Please type a valid email Address" + "<br>"
if($("#name").val() == "") {
errorMsg += ferrorMsg;
}
if($("#address").val() == "") {
errorMsg += aerrorMsg;
}
if($("#email").val() == "") {
errorMsg += eerrorMsg;
}
$(".errorContainer").html(errorMsg);
$(".overlay").remove();
}
The .errorContainer div is inside the .overlay div. When you remove overlay in the end of your function, errorContainer is removed too. Other than that, it seems the .html(errorMsg)
is working fine (if it still causing error, please specify what's going wrong).
Re-reading your question, I couldn't understand you program's flow: are you adding that div when the error is already known, and closing it when you click the "X"? If thats the case, I'd suggest doing something like this:
var errorMsg = "";
var ferrorMsg = "Please say your first name" + "<br>";
var aerrorMsg = "Please type address" + "<br>";
var eerrorMsg = "Please type a valid email Address" + "<br>"
if($("#name").val() == "") {
errorMsg += ferrorMsg;
}
if($("#address").val() == "") {
errorMsg += aerrorMsg;
}
if($("#email").val() == "") {
errorMsg += eerrorMsg;
}
// Adapting Diego's answer:
$("<div class='overlay'><div class='errorContainer'></div><div><a href='javascript:void(0);' class='cross'>X</a><div></div>")
.appendTo($("body"))
.find(".errorContainer")
.html(errorMsg)
.end()
.find(".cross")
.click(function(e) {
e.preventDefault();
$(this).closest(".overlay").remove();
});
I think you meant:
//generates a div onclick of submit button
$("body").append("<div class='overlay'><div class='errorContainer'></div><div><a href='javascript:void(0);' class='cross'>X</a><div></div>").find(".errorContainer").html(errorMsg);

Categories