How to search particular word in a input field - javascript

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

Related

getting data from input box in form using jquery

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

JavaScript string is not a function

When working on a page whenever I call on my second function, validateNumber(), I get a "typeError: String is not a function" message can anyone explain to me why this message is occuring? My code is as follows:
< script type = "text/javascript" >
/* <![CDATA[ */
function validateLetter(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
dataEntry.value = replacedInput;
} catch (textInputError) {
window.alert(textInputError)
return false;
}
return true;
}
function validateNumber(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if (textInput != replacedInput)
throw "You can only enter numbers into this field.";
} catch (numberInputError) {
window.alert(numberInputError)
return false;
}
return true;
}
function validateInput(dataEntry) {
if (navigator.appName == "Microsoft INternet Explorer")
var enteredKey = dataEntry.keyCode;
else if (navigator.appName == "Netscape")
var eneteredKey = dataEntry.charCode;
}
/* ]] */
< /script>
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded" name="dataEntry">
<p>Enter your mother's maiden name:
<input type="text" id="letter1" name="letter1" onkeypress="validateLetter(this)">
</p>
<p>Enter the city you were born in:
<input type="text" id="letter2" name="letter2" onkeypress="validateLetter(this)">
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter3" name="letter3" onkeypress="validateLetter(this)">
</p>
<p>Enter your phone number:
<input type="text" id="number1" name="number1" onkeypress="validateNumber(this)">
</p>
<p>Enter the year you were born:
<input type="text" id="number2" name="number2" onkeypress="validateNumber(this)">
</p>
<p>Enter the number of siblings you have:
<input type="text" id="number3" name="number3" onkeypress="validateNumber(this)">
</p>
<p>
<button type="reset" value="Reset Form">Reset Form</button>
</p>
</form>
I am almost certain this is the problem:
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if textInput is a string you cannot pass parameters to it as if it were a function, instead:
var replacedInput = textInput.replace(/[^0-9]/g, ""); // dependening in what you are trying to achieve of course
var replacedInput = textInput(/[^0-9]/g);
That's not how you do search and replace in Javascript.
It's not quite clear what you intended here, but if you wanted to remove non-digits from the string, you'd do that using String.replace():
var replacedInput = textInput.replace(/[^0-9]/g, "");
That being said, an easier way of accomplishing this check would be to skip the replacement entirely and just use String.match() instead:
var textInput = dataEntry.value;
if (textInput.match(/[^0-9]/))
throw "You can only enter letters into this field.";
dataEntry.value = textInput;
You might consider isolating functionality so that functions like validateLetter simply validate that the string they are passed contains only letters, then have the caller function work out what to do if the return value is true or not.
In that case, you end up with very much simpler functions:
function validateLetters(s) {
return /^[a-z]+$/i.test(s);
}
function validateNumbers(s) {
return /^\d+$/.test(s);
}
To validate an input, you can add a class to say what type of validation it should have, e.g.
<input name="letter3" class="letter" onkeypress="validateLetter(this)">
Then the validateInput function can determine which validation function to call based on the class:
function validateInput(element) {
var value = element.value;
// If has class letter, validate is only letters
if (/(\s|^)letter(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateLetters(value) && value != '') {
alert('Please enter only letters');
}
}
// If has class number, validate is only numbers
if (/(\s|^)number(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateNumbers(element.value) && value != '') {
alert('Please enter only numbers');
}
}
}
Note that keypress is not a good event to use for validation as data can be entered without pressing any keys (e.g. paste from the context menu or drag and drop). Also, the listener doesn't see the value resulting from the keypress, it sees the previous value.
You really only need to perform validation when the form is submitted. Until then, why do you care what the values are? Allow the user to make mistakes and fix them themselves without being pestered by alerts (onscreen hints are really useful). Spend some time using your forms to enhance their usability (I realise this is probably not a production form, but names can have characters other than the letters a to z, e.g. von Braun and O'Reilly).
Lastly, form controls rarely need an ID, the name is usually sufficient to identify them if required (and they must have a name to be successful, so most have a name already). A bit of play HTML from the OP:
<form>
<p>Enter your mother's maiden name:
<input name="letter1" class="letter" onkeypress="validateInput(this)">
</p>
<p>Enter the number of siblings you have:
<input name="number3" class="number" onkeypress="validateInput(this)">
</p>
<p>
<input type="reset">
</p>
</form>

Only allow HTML field to start with certain words

Is there a quick javascript library or code that would only allow a user to start a form input with a preset selection of words?
For example it would allow a user to start a the word "Are" or "What" but not "Why".
You can use the following Regex. (This is really primitive and should be improved according to your case.)
^(Why|Are).*$
HTML5 input pattern example:
<form>
<input type="text" pattern="^(Why|Are).*$">
<input type="submit">
</form>
Test here.
You can add change or input event listener to it and validate the content. To avoid false negatives with initial few letters you can start checking after the input string contains a space. You don't need a library to do that. Plain old JS will do the job.
var input = document.getElementById("myinput");
input.addEventListener('input', validate);
function validate(e) {
var validStart = ['why', 'when'];
var tmpVal;
if (this.value.indexOf(' ') !== -1) {
tmpVal = this.value.toLowerCase().trim();
if (validStart.indexOf(tmpVal) === -1) {
input.classList.add('notvalid');
} else {
input.classList.remove('notvalid');
}
} else {
input.classList.remove('notvalid');
}
}
JSFiddle: http://jsfiddle.net/ofx2yhzm/1/
Very similar to Strah's answer, but here it is anyway:
function checkValue(el) {
// Trim only leading whitespace so responds when first space entered
// and break into words
var words = el.value.replace(/^\s+/,'').split(/\s+/);
// List of allowed words
var allowed = ['are','what'];
// Element to write message based on source element
var msg = document.getElementById(el.id + 'Msg');
// Clear error message by default
msg.innerHTML = '';
// Only do something if at least one word has been entered
// Could also check if first word has more letters than
// longest allowed word
if (words.length > 1) {
// Check if first word is allowed
if ( allowed.indexOf(words[0].toLowerCase()) == -1) {
msg.innerHTML = 'Input must start with one of ' + allowed.join(', ');
}
}
}
Some markup:
<input id="foo" oninput="checkValue(this);">
<span id="fooMsg"></span>
This allows the user to at least enter a word before being given an error. They should also be given some onscreen hints to let them know which words to use, rather than having to get it wrong first (which is bound to happen a lot).
Html:
<form name="myform" method="post" action="#" onsubmit="return validate()">
<input type="text" name="val" />
<input type="submit" value="Submit" />
</form>
Javascript:
window.validate = function(){
data = document.forms['myform']['val'].value;
var starts = ['hi','he'];
for (var i = 0; i <= starts.length; i++)
if (data.indexOf(starts[i]) === 0) return true;
return false;
}
And of course you could also use Regex tho I guess that's a little more inefficient.
Something like this?: http://jsfiddle.net/4jasrbob/

JavaScript empty field validation does not work

So, I have a number textbox and I want to validate it using JavaScript. If the user has not input any number, it will prompt him/her to enter one. My codes below:
<input type="number" autofocus id="lol"/>
<input type="button" onClick="validate()" value="Input"/>
<script>
function validate() {
var numfield = document.getElementById("lol").value;
if ( numfield == "") {
document.write("Missing number!");
}
</script>
What is wrong?
You have missed a } at the end of the script. With that fixed, it works normally.
Try to use length property.
if ( numfield.length > 0) {
...
}

If number is = to 25

I would like to have a text field that a user can enter a number and if the number is correct it the displays "image a" and if incorrect displays "image b" below the text field i want them to have as many tries as they like to get it correct. The only thing i have found so far is this?
sorry about the lack of experience guys :(
var my_string = prompt("Please enter a number","");
document.write(my_string)
if(isNaN(my_string)){
document.write ("this is not a number ");
}else{document.write ("this is a number ");
}
The user will enter characters, so you'll have to compare strings. You can use the === operator which checks equality; you'll have to check against the string "25".
Then, to display the image, you'll have to give the images in HTML an ID. After doing so, you can fetch the element in JavaScript using document.getElementById("some_id"). Showing/hiding is done using element.style.display = "block" vs "none".
Heres code sniplet:
<script type="text/javascript">
function check_number()
{
var num = document.getElementById('input_number').value;
var img = num == '25' ? 'good.png' : 'bad.png';
document.getElementById('result_image').src = img;
document.getElementById('result').style.display = 'block';
}
</script>
<input type="text" id="input_number"
<input type="submit" onclick="check_number();return false;">
<div id="result" style="display:none;">
<img src="blank.png" alt="" id="result_image">
</div>
This will get you started
var my_string = prompt("Please enter a number","");
document.write(my_string);
if(my_string === '25'){
document.write('Yesss');
} else {
document.write('Wrong');
}

Categories