JQuery if input starts with a value - javascript

I am managing to check the value inside a postcode input field using the following:
html:
<input type="text" class="cart-postcode2" size="10" tabindex="22">
JQuery:
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.indexOf('BT') >= 0) {
alert("is ireland");
}
})
This is working great however I want it to only alert if it starts with BT and does not contain BT in any part of the value, does anyone know if this is possible?
So typing BT2 9NH will alert "Ireland" but typing OX2 8BT will not

You can check if string starts with BT, as indexOf() will give index zero if value stats with BT
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.indexOf('BT') == 0) {
alert("is ireland");
}
})

a regex solution:
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.match(/^BT/)) {
alert("is ireland");
}
})

Related

Clear invalid input field only

[Visualforce page] I have 3 input fields with class name rowStyle3 and it accepts numberic character only.
When the user enters a non-numeric character, I want the only invalid input field is cleared.
please help me to correct code snippet below.
Thanks a lot
<script>
$(document).ready(function() {
$(document).on("change", ".rowStyle3", function() {
$('.rowStyle3').each(function() {
var num = $(this).val();
if(num != "" && isNaN(num)){
$(".rowStyle3").val(''); -> All values of input fields will be cleared if one of them is invalid
alert("Allow numbers only !");
}
});
});
});
</script>
This should do the trick.
$(document).ready(function() {
$(document).on("change", ".rowStyle3", function() {
$('.rowStyle3').each(function(row) {
var num = row.val();
if(num != "" && isNaN(num)){
row.val('');
alert("Allow numbers only !");
}
});
});
});
Instead of doing $.(this) you can use the enumerated value of the foreach.
You can use ValidityState to check whether input element is invalid or not:
if (!inputElement.validity.valid) {
inputElement.value = '';
}
This checks whether the inputElement input is invalid, if so, it clears it. InputElement should be something like (given that your input id is name):
inputElement = document.getElementById("name")

compare Two field if the field is in the content of other field using javascript after submit button clicked

Hi I am not a javascript expert thats why I will really appreciate any advice
I have a textfield named try where in I will input something
ex:
try value is
87
then I have another textfield named field11
field11 has a value of
777-a98;87-bx23;000-t88;245-k7
I wanted to compare try and field11 if try is found in the content of field 11 it will set the textfield named msg to 87-bx23 matched
msg value will be
87-bx23 matched
my code is like this but its not giving the desired output I know my comparison is wrong it just I dont know how
<script>
$(document).ready( function(){
$('#submit').click(function() {
if (document.getElementById('try').value != document.getElementById('field11').value)
{
alert('dont match!');
$("#msg").val ("dont match!");
}
else if (document.getElementById('try').value == document.getElementById('field11').value) {
}alert(document.getElementById('try').value + " exists");
$("#msg").val(document.getElementById('try').value + " exists");
});
});
</script>
I also try this but if I input 77 it saying it exist even not
<div id="requirement #2">
<button type="button" id="button2" onclick="StringSearch()">Search</button>
</div>
<script>
function StringSearch() {
var SearchTerm = document.getElementById('try').value;
var TextSearch = document.getElementById('field11').value;
if (SearchTerm.length > 0 && TextSearch.indexOf(SearchTerm) > -1) {
alert("Patient Exists");
} else {
alert("Patient Does not exist click add if you want to add the patient");
$("#msg").val(document.getElementById('try').value + " exists");
$("#t1").val("1");
}
}
</script>
document.getElementById('field11').value.match(new RegExp("(" + "87" + "-[a-z0-9]+);"))[1])
The Generated Regex when try value = 87:
/(87-[a-z0-9]+);/
So what is this monstrosity? We generate a Regex Expression, that looks for the try value followed by a dash, and one or more characters from a-z or 1-9, followed by a semicolon. String.match() is used to determine an array of matches, the array[1] is the first capture group (the part of the RegEx between the brackets), which is in this case 87-bx23
I have tried to rewrite your code to store variables for the elements and use a Regexp to do the search for the value:
<script>
$(document).ready( function(){
var tryElem = document.getElementById('try');
var field1 = document.getElementById('field11');
$('#submit').click(function() {
var regex = new Regexp(tryelem +'[^;]*');
var match = regex.exec(field.value);
if (match)
{
alert(match + " exists");
$("#mag").val(match + " exists");
}
else
{
alert('dont match!');
$("#msg").val ("dont match!");
}
});
});
</script>
The code does more or less the same as yours, except for the regex:
tryelem +'[^;]*'
It builds a regular expression form the the value of tryElem and then it searches forward and matches up to the first semi colon (zero or more characters).
Now the match will contain: '87-bx23'.
You can try this:
<input type="text" id="try"/>
<input type="text" id="field11" value="777-a98;87-bx23;000-t88;245-k7"/>
<input type="text" id="msg"/>
<input type="button" id="submit"/>
And js:
$(function(){
$("#submit").click(function(){
var Try=$("#try").val(),
f11=$("#field11").val(),
msg=$("#msg");
//but if you want search in number part only (before dash sign), uncomment line below and comment next line.
//var r=((";"+f11+";").match(new RegExp(";([^;-]*"+Try+".*?-.+?);"))||[])[1];
var r=((";"+f11+";").match(new RegExp(";([^;]*"+Try+"[^;]*);"))||[])[1];
msg.val(r||"don't match!!");
});
});
You can check or change both of them online

check if text exists in text box jquery

how to check if the text exists in text box jquery
I need to check if the text exists in the input box,if checking text is not exist thend append new data
I have tried with below code
$(document).ready(function(){
$("#item_inv_desc").change(function(){
var item_inv_desc = $('select[name=item_inv_desc]').val();
if (item_inv_desc == 7)
{
var invoice_number = "123456789";
//I need check if text "CRN" exists in text box
var data=$('#invoice_number:contains("CRN")')
if(data)
{
//if text "CRN" exist no need to append data
}
else
{
//if not exist
$("#invoice_number").val(invoice_number+"CRN");
}
}
});
})
//Html
<input type="text" id="invoice_number" value="">
I am having problem when try to insert append value it adds extra CRN number to invoice number,I need to avoid duplicating,
Try includes() with the val() of the text box:
var data = $('#invoice_number').val().includes("CRN")
or, for older browsers, use indexOf():
var data = $('#invoice_number').val().indexOf("CRN") !== -1
Working Demo:
$(document).ready(function() {
$("#invoice_number").change(function() {
var invoice_number = "123456789";
var data = $('#invoice_number').val().includes("CRN");
if (data) {
} else {
$("#invoice_number").val(invoice_number + "CRN");
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="invoice_number" value="">
You can use regex to remove all the digits and get the text only from the value of the input text. If you want that on button click then add that block of code inside the click function:
var data = $('#invoice_number').val();
var res = data.replace(/[0-9]/g, '');
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="invoice_number" value="123456789CRN">
#Manjunath
var data=$('#invoice_numbe:contains("CRN")')
"r" is missing when you are checking below
var data=$('#invoice_numbe:contains("CRN")')
and use
var data=$('#invoice_number').val().indexOf("CRN");
if(data>-1){
// donot add CRN
}

How to add or subtract number to html element with jquery

I am trying to add/subtract from a number inside a span tag. This is depenent on a checkbox. Here is the jquery I'm trying:
//If checked
var $newprice = $("#totalprice").val() + 299;
$("#totalprice").text($newprice);
//If NOT checked
var $newprice = $("#totalprice").val() - 299;
$("#totalprice").text($newprice);
If I check the box, it adds 299, but unchecked changes the number to -299.
For span you need to use text() method to get content not val(). In both case val() returns an empty string. In first case just string concatenation will be happen. In second case it will be "" - 231 which results -231, where the empty string act as 0.
So you can use text() with callback which hold index and old value, parse the old value and add or subtract value and return it for update.
//If checked
var $newprice = $("#totalprice").text(function(i,v){
return parseInt(v,10) + 299;
});
//If NOT checked
var $newprice = $("#totalprice").text(function(i,v){
return parseInt(v,10) - 299;
});
You have to do this in change event of your checkbox:
$(':checkbox').change(function() {
if (this.checked) {
//If checked
var $newprice = +$("#totalprice").text() + 299;
$("#totalprice").text($newprice);
} else {
//If NOT checked
var $newprice = +$("#totalprice").text() - 299;
$("#totalprice").text($newprice);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type='checkbox'>
<span id='totalprice'>0</span>
</p>
+$("#totalprice").text() leading + would turn the text to number.

if input field is not a number OR not empty replace with a number

I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle

Categories

Resources