I am trying to validate a form's input value after clicking a button using jQuery and javascript.
Right now, if I put in a value for the input and click submit the input field and button just disappears. Any idea what I have wrong here?
The HTML file...
<!DOCTYPE html>
<html>
<head>
<title></title>
<link/>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<form>
<input type="text" id='input_1'>
<input type="submit" value="Send" id="send">
</form>
</body>
</html>
The script file...
$(document).ready(function() {
$('.send').click(function() {
validateInput(document.getElementById('#input_1'));
function validateInput(inputValue){
if (inputValue === 3) {
alert("Element cannot be equal to 3");
}
}
});
});
$(document).ready(function() {
$('#send').live('click',function() { //Because send is the id of your button
if(validateInput(document.getElementById('#input_1'))){
alert("Element cannot be equal to 3");
return false;
}
else{
//Do something else
}
function validateInput(inputValue){
if (inputValue == 3) {
return false;//Will prevent further actions
}
}
});
});
this $('.send').click(function() {
should be $("#send").click(function() {.
Notice the Hash symbol and not the dot (.), dot is used if the selector is a class whereas the # is used if the selector is an ID.
2.You should move the validation function outside the $(document).ready(function().. Hope that helps
Thank you all for your responses. Unfortunately, I wasn't able to get it to work using your recommendations. I decided to use jQuery to get the element and appended a message to a div instead of using alert. This was a different approach but ended up working.
HTML...
<!DOCTYPE html>
<html>
<head>
<title></title>
<link/>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
<input type="text" name="input"/>
</form>
<button id="send">Send</button>
<div class="error">
</div>
</body>
</html>
SCRIPT...
$(document).ready(function() {
$('#send').click(function(){
var toValidate = $('input[name=input]').val();
if (toValidate == 3) {
jQuery('.message').html('');
$('.error').append('<div class="message">' + toValidate + " is invalid" + '</div>');
}
else {
jQuery('.message').html('');
$('.error').append('<div class="message">' + toValidate + " is valid" + '</div>');
}
});
});
Related
I have some code that returns an Uncaught SyntaxError when I run it but I don't understand why.
I tried putting it through JSHint but to no avail.
Here is the code that is apparently wrong:
function compute(expr, x, string) {
var whatisx = "x=" + toString(x) + ",";
var tempAns = parseFloat(eval(whatisx + expr));
var roundedAnswer = roundNumber(tempAns, 3);
if (isNaN(tempAns) === true) {
alert("error");
}
if (string) {
return toString(roundedAnswer);
} else if (!string) {
return roundedAnswer;
} else {
return null;
console.log("Error trying to compute value. The string value must be boolean.");
}
}
When I run it, I don't get any console logs and it says there is an error at the plus sign in:
var tempAns = parseFloat(eval(whatisx + expr));
Another problem in the same program that is also a SyntaxError is in my HTML.
Here is my html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Grapher</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js" charset="utf-8"></script>
<script type="text/javascript" src="functions.js" charset="utf-8"></script>
<script type="text/javascript" src="sketch.js" charset="utf-8"></script>
</head>
<body>
<form>
<label>Graph y=</label>
<input id="mathExpr" type="text" name="mathExpr" value="">
<label> from x=</label>
<input id="x_min" type="text" name="x_min" value="">
<label> to </label>
<input id="x_max" type="text" name="x_max" value="">
<input type="button" name="result" value="Result" onclick="compute(); runp5();">
</form>
<h2>Answer: <span id="output"></span></h2>
</body>
</html>
For this one, it says there is an error at
<input type="button" name="result" value="Result" onclick="compute(); runp5();">
What can I do to fix both of those?
Thanks in advance.
Edit: Question resolved. I was calling compute without any parameters. (thanks #Pointy)
I came back to this question just now, and I realized I was making another mistake. Here is my fix:
As user Pointy noticed, I was calling compute() without its required parameters.
I should add console.log() in my else statement before the return otherwise it won't get called at all:
// ...
else {
console.log('message'); // this should come before return
return null;
}
This doesn't actually fix the problem I detailed, but I wanted to point it out for any future readers.
I am new to jQuery.
Simply I want to build a password show/hide program.
I have written some code (below), and the first time the program works correctly - the password is showing after clicking on "Show" button. But then the "Hide" feature is not working.
In my code the if part is running each time but the else part never executes. What's wrong here?
$("#btn").click(function() {
if ($("#pass").attr("type", "password")) {
$("#pass").attr("type", "text");
$("#btn").attr("value", "Hide")
} else {
$("#pass").attr("type", "password");
$("#btn").attr("value", "Show")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Password : <input type="password" id="pass">
<input type="button" id="btn" value="Show">
The problem is this line:
if($("#pass").attr("type","password")){
$("#pass").attr("type","password") is setting the value of the "type" attribute, not comparing it to anything. What you need to do is get the value, and then compare it to the value you're checking for:
if($("#pass").attr("type") == "password")) {
Here is a full working example:
N.B. I also added variables to represent the button and textbox, because it's inefficient to repeatedly invoke the jQuery constructor on the same elements.
$(document).ready(function() {
var btn = $("#btn");
btn.click(function() {
var pass = $("#pass");
if (pass.attr("type") == "password") {
pass.attr("type", "text");
btn.attr("value", "Hide")
}
else {
pass.attr("type", "password");
btn.attr("value", "Show")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Password show/hide in Jquery</title>
</head>
<body>
Password : <input type="password" id="pass">
<input type="button" id="btn" value="Show">
</body>
</html>
You may also wish to review the jQuery documentation to help your understanding: http://api.jquery.com/attr/
<!DOCTYPE html>
<html>
<head>
<title>WhiteList</title>
</head>
<body>
<h1>Hello stranger lets see if you are on the list!!</h1>
<input id="1" value="type here" placeholder="type here">
<button onclick="click()">Check</button>
<br>
<p id=stuff></p>
<script type="text/javascript">
function click(){
var name = document.getElementById('1').value;
if (name == "tijmen"){
document.getElementById("stuff").innerHTML = "<p>hey you are on the list welcome</p>"
} else{
document.getElementById("stuff").innerHTML = "<p>sorry you are not on the list</p>"
}
}
</script>
</body>
</html>
so this is the code, there are no errors. but the problem is that the text won't print when i insert my name and click the button.... i realy cant seem to find the problem.
Try add onclick to the JavaScript:
<body>
<h1>Hello stranger lets see if you are on the list!!</h1>
<input id="1" value="type here" placeholder="type here">
<button id="btn">Check</button>
<br>
<p id=stuff></p>
<script type="text/javascript">
document.getElementById("btn").onclick = function() {
var name = document.getElementById('1').value;
if (name === "tijmen"){
document.getElementById("stuff").innerHTML = "<p>hey you are on the list welcome</p>"
} else {
document.getElementById("stuff").innerHTML = "<p>sorry you are not on the list</p>"
}
}
</script>
</body>
Problem here is click is defined as a click action so the engine is thinking you are calling the click of the button. Simple test shows what the browser sees.
<button onclick="console.log(click)">Check</button>
What can you do? Change the name, or even better, use addEventListener to bind the event listener.
I have a code and I want that after the user type something in the textfield and press enter, what he typed appears on the screen. But I'm not being able to do that, I'd like some help here.
<!DOCTYPE html>
<html>
<head>
<title>Tasks for the day</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
alert("When you have finished your task you only have to click on it.");
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
$(document).keypress(function(e) {
if(e.which == 13) {
}
});
function showMsg(){
var userInput = document.getElementById('userInput').value;
document.getElementById('userMsg').innerHTML = userInput;
}
</script>
</head>
<body>
<h1>Tasks to do</h1>
<p>Type what you need to do:</p>
<input type="input" id="userInput" onkeyup=showMsg() value="" />
<p id="userMsg"></p>
</body>
</html>
it only adds one value to the screen, to put more than one, do I need
to create an array
You had the main components working. Namely, you were updating the screen. To have it update only on enter, simply put the code in the keypress handler
To append the value to the screen(in the case of more than one enter), concatenate the current innerHTML with the value
$(document).ready(function() {
$("p").click(function() {
$(this).hide();
});
});
$('#userInput').keypress(function(e) {
if (e.which == 13) {
var userInput = document.getElementById('userInput').value;
var innerHTML = document.getElementById('userMsg').innerHTML;
innerHTML = innerHTML || '';
document.getElementById('userMsg').innerHTML += innerHTML + userInput;
}
});
<title>Tasks for the day</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<h1>Tasks to do</h1>
<p>Type what you need to do:</p>
<input type="input" id="userInput" onkeyup=showMsg() value="" />
<p id="userMsg"></p>
<html>
<head>
<title></title>
<script >
fields = 0;
function addInput() {
if (fields != 3) {
document.getElementById('text').innerHTML += "<input type='text' name='clients_form[clients_name]' size='32' maxlength='32' value='' id='clients_form_clients_name_"+fields+"' />"+
'<select id="client_category_name_'+fields+'" name="client_category[]"><option value="">Select Category</option><option value="1">internal</option><option value="2">external</option><option value="3">others</option></select>';
fields = fields+ 1;
} else {
document.getElementById('text').innerHTML += "<br />More then 3 not allowed.";
document.form.add.disabled=true;
}
}
</script>
</head>
<body>
<form name="form">
<input type="button" onclick="addInput();" name="add" value="Add More" />
</form>
<div id="text">
</div>
</body>
</html>
Question: When I click on add more first and type something and click on add more again the one i entered before is removed. What is the reason behind this. And how to fix it?
Thanks In advance
.innerHtml replaces the content which you place next..so use append like
var t = document.createElement("div"),
document.getElementById("theBlah").appendChild(t);
Problem is that typing something in the input does not change its value parameter but sets its value property (know the difference), e.g. it changes this.value instead of this.attributes.value, which results in innerHTML not actually containing the typed value.
So since innerHTML += 'string' ist just like setting innerHTML = innerHTML + 'string', it resets the input value to its attribute, which is empty.
I'd really recommend to use jQuery here, because with pure JS you'd have to first create the input and select element, then apply all needed attributes with multiple .setAttribute() calls.
I used Jquery and solved it this way:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
var counter = 1;
$("#addButton").click(function () {
if(counter>6){
alert("Not allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html(Added my text box and select tag here);
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
</div>
</div>
<input type='button' value='Add More' id='addButton'>
<input type='button' value='Remove' id='removeButton'>
</body>
</html>