getting data from input box in form using jquery - javascript

This is a form I have:
<h1>Word game!</h1>
<form id="joke-form">
<label>
Unscramble these letters to form a word:<Br>
<span class="scrambled">REYJUQ</span>
<br>
<input type="text" id = "userinput" size="10">
</label>
<button type="submit">Check</button>
</form>
And here is a jquery function I am running on it. My problem is that I don't know how to get the value that the user inputs in the textbox when they press submit. I am relatively new to jquery but have had no luck in researching this topic, including reading similar questions on this site.
<script>
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('this input: first').val();
console.log(words);
});
if (words === "ANSWER") {
$('#result').text("You have the right answer");
}
else {
$('#result').text("Guess again!");
}
</script>

You have the code in the wrong place, and the selector you are using is incorrect for the input.
See this codepen on how this could work:
http://codepen.io/KempfCreative/pen/JGRzwm
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('#joke-form #userinput').val();
console.log(words);
if (words === "ANSWER") {
$('#result').text("You have the right answer");
}
else {
$('#result').text("Guess again!");
}
});

Try:
var words = $('#userinput').val();

Your selector $('this input: first') is malformed. Since your input element has an id anyway, I would just select it by id instead. Also you will need to put your if else statement inside the submit function.
Here is a Live Demo of your code working in action:
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('#userinput').val();
console.log(words);
if (words === "JQUERY") {
$('#result').text("You have the right answer");
} else {
$('#result').text("Guess again!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Word game!</h1>
<form id="joke-form">
<label>
Unscramble these letters to form a word:
<Br>
<span class="scrambled">REYJUQ</span>
<br>
<input type="text" id="userinput" size="10">
</label>
<button type="submit">Check</button>
</form>
<span id="result"></span>
JSFiddle Version: https://jsfiddle.net/6pd5z9kv/1/

I see many anwsers already but here is what you've done wrong
your code
var words = $('this input: first').val();
fixed
var words = $(this).find("input:first").val();
//use 'this' seprately, then you start input:first with " and finished with '
hopefully it will work for you, and about html I dont know if its copy/pase issue but remove blank space with id and =
your code
id = "userinput"
fixed
id="userinput"
Rest is just fine :)
Cheers

Related

How to search particular word in a input field

I'm trying to search a particular word on the input field and perform if/else condition accordantly. for an example input field can be "iPhone 6" or "Apple iPhone 5" or " Samsung A7" o "S9 Samsung" etc. Please help me find word "iPhone" or "Samsung" from the input field apply if/ else condition.
<input type="text" id="ModelNo" />
<script>
var Model_Validation = document.getElementById("ModelNo").value;
var Model_1 = "iPhone";
var Model_2 = "Samsung";
function test() {
if (Model_Validation == Model_1) {
} else if (Model_Validation == Model_2) {
} else {}
}
</script>
I doubt which logic to use in if condition as well. hope my question is clear.
You can use the includes method on your input's text.
let input = document.getElementById("ModelNo").value;
if(input.includes(Model_1)){/* do something*/}
else (input.includes(Model_2)){/* do something else*/}
Or you can use a regular expression but includes should be more efficient and simple for what you want to do.
This could be achieved with JQuery:
<input id="search" type="input" value="type here"/>
<div id="result"></div>
$(document).ready(function(){
$("#search").on('input',function(){
var userinput = $(this)[0].value;
if(userinput == 'samsung'){
$("#result").html('user inserted "samsung"');
}
else{
$("#result").html(userinput);
}
})
});
Working example here

Javascript getElementByID from form input

I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>
So, the user shall enter for instance "1+2". The result shall appear below.
Any idea where is my mistake?
Best regards
Here is how you can achieve that.
eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.
I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.
remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13
num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
if(e.which==13)
{
var value = num_field.value.match(/(^[-+/*0-9]+)/g);
if(!value) return;
else value = value[0];
var res = eval(value);
document.getElementById("display_result").innerText = res;
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calc" />
<p id="display_result"></p>
You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)
The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post" id="form">
<span>Type here:</span>
<input type="text" id="calc"> <!-- inputs are self closing no need for closing tag -->
<input type="submit" value="submit"> <!-- added a submit button -->
</form>
<script>
form = document.getElementById("form");
num_field = document.getElementById("calc");
form.onsubmit = function() { // attach this event to the form
document.getElementById("display_result").innerHTML = evalAlternate(num_field.value); // add .value here to get the value of the textbox
return false; // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
}
function evalAlternate(fn) { // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
fn = fn.replace(/ /g, "");
fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
return new Function('return ' + fn)();
}
</script>
<p id="display_result"></p>
</body>
</html>
see the below fiddle
https://jsfiddle.net/ponmudi/13y9edve/
num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
if (event.keyCode === 13) {
document.getElementById("display_result").innerHTML = eval(num_field.value);
return false;
}
}
This should work:
calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>
eval() JavaScript Method
Try this:
var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
if (event.keyCode == 13) { // Enter key.
// Sanitize before using eval()
var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
document.getElementById("display_result").innerHTML = eval(calculation);
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>
You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)

jQuery Click Function, input value length and pattern

I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.

change <p> to input value when click button

I've got this code
HTML
<h2 class="p1">Player 1</h2>
<input type="text" class="addName1" value="Player 1"></input><button class="addName1b">Add name</button>
Jquery
$('.addName1b').click(function() {
var $this = $(this);
$this.toggleClass('addName1b');
if ($this.hasClass('addName1b')) {
$this.text('Add name');
} else {
$this.text('Change name');
}
$('.addName1').toggle();
$(/*TEXT FROM INPUT*/).appendTo(".p1");
});
I want the Player 1 to change into the text from the input box when I press the button but can't figure out how. Help please :)
As you can see I was planning on using .appendTo but I don't know how to access the text from the input element.
Thanks
Use it this line of code
$('.p1').text($('.addName1').val());
in the place where you have $(/*TEXT FROM INPUT*/).appendTo(".p1");
appendTo is not the right choice for your goal here, appendTo is used to append elements into another, but your requirement is to change the text of the element, you must use .text()
Here is a working snippet.
$('.addName1b').click(function() {
var $this = $(this);
$this.toggleClass('addName1b');
if ($this.hasClass('addName1b')) {
$this.text('Add name');
} else {
$this.text('Change name');
}
$('.addName1').toggle();
$('.p1').text($('.addName1').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 class="p1">Player 1</h2>
<input type="text" class="addName1" value="Player 1"></input><button class="addName1b">Add name</button>
Used a variable to store the new name,
Got the new name from the input using .val()
Reversed the last line because the selector $('.p1')goes first then the value is last (newName).
There's no parentheses because it's a variable representing a string.
Change the last two lines to this:
var newName = $('.addName1').val();
$(".p1").text(newName);
$(function() {
$('.addName1b').click(function() {
var $this = $(this);
$this.toggleClass('addName1b');
if ($this.hasClass('addName1b')) {
$this.text('Add name');
} else {
$this.text('Change name');
}
var newName = $('.addName1').val();
$(".p1").text(newName);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<h2 class="p1">Player 1</h2>
<input type="text" class="addName1" value="Player 1" />
<button class="addName1b">Add name</button>
Maybe you should use some framework?) Something like angular, knockout, reactjs? Excellent for something like this purposes.
But. For reading input value you can use something like:
$('#id').val();
Input does not close like this
<h2 class="p1">Player 1</h2>
<input type="text" class="addName1" value="Player 1"></input><button class="addName1b">Add name</button>
just
<input .... />
Your JS - modified
$('.addName1b').click(function() {
var $this = $(this);
var $input_val = $('.addName1').val();
$this.toggleClass('addName1b');
if ($this.hasClass('addName1b')) {
$this.text('Add name');
} else {
$this.text('Change name');
}
$('.addName1').toggle();
$('.p1').text($input_val);
});
here's jsfiddle: https://jsfiddle.net/qgumjy7b/
Hope this helps to understand what are you missing.

jQuery - Code to check if any of the fields are not empty, and then make all of them required

I am a PHP developer and new to jQuery, I just wrote a few lines of code before and it was all from online sources. Anyways, I have these three inputs in html:
<input type="password" name="old-password" id="old-password">
<input type="password" name="new-password" id="new-password">
<input type="password" name="confirm-new-password" id="confirm-new-password">
<button type="submit" id="save" class="button button-primary">Save Changes</button>
I have a full page of settings and these three fields are for passwords, but I want to make them required only if the user enters any data into any of the inputs.
Example: A user types in old password input, all 3 inputs gets required real-time. Or a user types in confirm new password input, all 3 inputs gets required as well.
Thank you for the help.
Solution: The answers were all great and thank you everyone for the help. Another problem came up, is that if someone tries to backspace and remove the text on the form, it still stays required. I came up with a solution with the help of all the answers.
You have to add a .password class to all the wanted inputs, and then put this in script tags:
$('.password').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$('#old-password').removeAttr('required', '');
$('#new-password').removeAttr('required', '');
$('#confirm-new-password').removeAttr('required', '');
} else {
$('#old-password').attr('required', '');
$('#new-password').attr('required', '');
$('#confirm-new-password').attr('required', '');
}
});
Use .attr() on the oninput event.
i.e. something like this:
function makeRequired(){
$("#old-password").attr("required","");
$("#new-password").attr("required","");
$("#confirm-new-password").attr("required","");
}
And then bind it to oninput either in your HTML or in JS.
Using your condition
if the user enters any data into any of the inputs.
You could write this event
$("body").on("input", "#confirm-new-password,#new-password,#old-password", function()
{
$("#confirm-new-password").attr('required', 'required');
$("#new-password").attr('required', 'required');
$("#old-password").attr('required', 'required');
});
well, I extremly recommend to use a library like Jquery validate jqueryValidate
But, if you don't want to use, you can try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<input type="password" name="old-password" id="old-password" class="passwordToCheck">
<input type="password" name="new-password" id="new-password" class="passwordToCheck">
<input type="password" name="confirm-new-password" id="confirm-new-password" class="passwordToCheck">
<button type="submit" id="save" class="button button-primary">Save Changes</button>
<script>
$(".passwordToCheck").change(function(){
passInput = $(this);
if(passInput.val().trim() != ""){
passInput.addClass("required");
} else {
passInput.removeClass("required");
}
});
$("#save").click(function(e){
e.preventDefault();
if($(".required").length >0){
alert("fill the fields!");
} else {
alert("OK");
$(this).submit();
}
});
</script>
adding a class to your password-type inputs, and working with required class ( you can change this easily by the required attr if you don't want to work with class required.
here is the fiddle:
jsfiddle
if ($("#old-password").val() != "" ||
$("#new-password").val() != "" ||
$("#confirm-new-password").val() != "") {
$("#old-password").attr("required");
$("#new-password").attr("required");
$("#confirm-new-password").attr("required");
}

Categories