Find and remove text from input value string - javascript

Our form has a hidden input that contains all the required values we send to the server for server-side validation. This is formed of a comma-separated string:
i.e. <input type="hidden" value="name,address,telephone,email">
We now have new inputs (i.e. website) that appear on a radio button check and I can successfully add these to the value="" string:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
$('input[name="required"]').val(nowReq + ',website');
}
But when a different radio is checked, I can't get it to remove ,website from the string.
I believe I need to grab the string, split it by comma, find and remove website and then re-join the string, but I'm not sure how to implement this (or if this is even the best way):
if ($('#fax').is(':checked')) {
var splitReq = nowReq.split(',');
// Something goes here?
$('input[name="required"]').val(nowReq2);
}

You can use string.indexOf(searchValue); and string.replace(oldValue, newValue); to search and remove non-selected elements or better pass Regular expression in the first parameter of string.replace(regex, newValue):
Non-regex Example:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
nowReq = nowReq + ',website';
}
else {
if(string.indexOf(',website') > -1) // If website is the last element
nowReq = nowReq.replace(',website', '');
else if(string.indexOf('website,') > -1) // If website is not the last element
nowReq = nowReq.replace('website,', '');
}
$('input[name="required"]').val(nowReq);

You simply need to remove the last element in your array and join it with the ',' character :
splitReq.pop();
$('input[name="required"]').val(splitReq.join(','));

Try:
var splitReq = nowReq.split(',website').join("");

the following would work in most cases:
var s = "name,address,telephone,email";
s = s.replace(",address", "").replace("address,", "").replace("address", "");

I'd suggest that you avoid parsing the value string, and simply recalculate the value on the change of the relevant input elements; the following is a demonstrative example because of the lack of information presented in the question (a more specific example could be provided if we can see your HTML, and current jQuery, rather than a description of it):
$('input[type="checkbox"]').on('change', function(){
var requiredString = $('input[type="checkbox"]').map(function(){
if (this.checked) {
return this.value;
}
}).get().join(',');
$('input[name="required"]').val(requiredString);
}).change();
JS Fiddle demo.
References:
change()
filter()
get()
map()
on()

Related

How to get the -real- last character typed in input with maxlength?

I wanted to know which character the user is typing into an input:
I have an input:
<input maxlength="20"/>
and a script that returns the last typed char:
var eingabe;
$('form').on('keypress', function(event) {
/// if no whitespace:
if (String.fromCharCode(event.keyCode).replace(/\s/g, "").length > 0) {
eingabe = String.fromCharCode(event.keyCode);
$('#eingabe').html("<div>Eingabe : "+ eingabe +"</div>");
}
});
My question is:
because my input has a maxlength attribute, the last typed character on the keyboard is sometimes not the last -real- typed character into the input because the input is "full". How can I get the last character typed into the input?
I haven't tried it, but it must work...
Set onkeypress= or onkeydown= on the Input element and store the key value in a LastChr variable.
I had a similar problem. I wanted to call a function if the user types a specific character into my input field. I solved it with the following:
var input = document.getElementById('myInput');
input.addEventListener('input', function() {
// Get cursor position
var start = this.selectionStart;
// Get last typed character
var lastChar = String.fromCharCode(this.value.charCodeAt(start - 1));
if(lastChar === '[YOURCHARHERE]') {
// do something
}
});
Please keep in mind, that 'input' is only supported down to IE8, but if you don't care about a proprietary browser, you should be fine. I hope this helps.
Inside your function, use the value of the input element to get the last character like $('#input_field').val().substr($('#input_field').val().length - 1) or use your best coding skill to accomplish something similar without accessing the field twice, wink wink.
Use keyup instead:
$('form').on('keyup', function(event) {
var cursorPos = event.target.selectionStart;
var lastTypedChar = elem.target.value[cursorPos - 1];
});

Javascript Regexp Format

I'm a beginner in JavaScript. I tried every tutorial/site and couldn't find an answer. I couldn't understand some examples.
I want to put a specific format and validate if the users input is correct.
Here is my code:
var expD = document.getElementById("ccN");
var re = new RegExp("[0-9][0-9]/[0-9][0-9]");
if (re.test(expD))
bootbox.alert("Correct");
else
bootbox.alert("Wrong");
expD is DOMElement, you cannot use it as if it is string
You need to bind event on textbox/button, to check if the value entered by user is in valid format
The regular expression needs ^ and $ anchors, if you want to check if the complete string is in the valid format
In your case expD is a dom element, I think you need to get the value and test it
function testit() {
var expD = document.getElementById("ccN").value;
var re = /^\d{2}\/\d{2}$/;
if (re.test(expD)) {
alert("Correct");
} else {
alert("Wrong");
}
}
<input id="ccN" />
<button onclick="testit()">Test</button>

Check if input fields contains certain text

I'm trying to find if what the user typing in to an input field contain certain text - I've kinda got it works, but only working for an exact match as opposed to a partial match. If a user types anything before the text i'm matching, of course the code doesn't trigger.
What i need to do is check if the input contains #nyu.edu at all in the input field.
$('.email').keyup(function(){
if ($(".email").val() == "#nyu.edu") {
$("p.warning").css("visibility", "visible");
}
else if ($(".email").val() != "#nyu.edu") {
$("p.warning").css("visibility", "hidden");
}
});
Checking if a string contains a substring is pretty easily done by taking haystack.indexOf(needle) and checking against -1 (not found).
if ($(".email").val().indexOf("#nyu.edu") !== -1) {
// contains
} else {
// does not contain
}
There is a function in the ES6 draft which you may find more natural, called includes
You can add support for ES6's String.prototype.includes like this
if (!String.prototype.includes) {
String.prototype.includes = function (needle, pos) {
return this.indexOf(needle, pos || 0) !== -1;
};
}
"foobar".includes('foo'); // true
Working Ex:
http://codepen.io/anon/pen/XJKMjo
$('.email').keyup(function() {
var exp = /#nyu\.edu$/; // reg ex
var input = $(this).val(); // email input
var matches = exp.test(input); // boolean
// changes to hidden or visible
$("p.warning").css("visibility", (matches) ? "visible" : "hidden");
});
You can filter based on HTML elements' attribute contents with jQuery to either contain, start, or end with a string that you want. To match elements with an attribute that contain a string, you'd use [attr*="value"] in your jQuery selector, but I think that you want something where the end matches your string. Here's how that would work:
var elements = $(".email[value$='#nyu.edu']");
if(elements.length > 0) {
// Do something with the elements, such as removing an .error class
} else {
// Email doesn't end with #nyu.edu
}
Read more about the jQuery ends-with attribute selector or browse through other attribute selectors like this.
jsBin demo
var $warning = $("p.warning"); // P.S. make sure not to target a wrong .warning!
$('.email').on("input", function(){
$warning.toggle( /#nyu\.edu/ig.test(this.value) );
});
as I've mentioned .warning being a class can represent any first .warning occurrence. use rather some other selector like .next() or .closest(selector).find(".warning")
your boss fill fire you if your client loses $$$ cause you forgot to watch for copy-paste cases. ;) Kidding, use "input" event.
P.S use .warning{display:none;} instead of visibility

Javascript Jquery: extract string from value and compose URL with this string

I am using an autocomplete Javascript function, and I need to extract the last 5 characters from 'value' and then compose URL for onSelect.
The function I am using is:
<script type="text/javascript">
var options, a;
jQuery(function(){
var onAutocompleteSelect = function(value, data) {
window.open('ITEM.PRO?id='+ value);
}
options = {
serviceUrl:'JQUERY-SEARCH.pro',
onSelect: onAutocompleteSelect,
};
a = $('#query').autocomplete(options);
});
</script>
When I click on search result it loads "ITEM.PRO?id=Article Brand Model Year Description 35612", but I need load "ITEM.PRO?id=35612"
Please could you help me? I am a totally newbie with JS.
Thank you all in advance!
Instead of window.open('ITEM.PRO?id='+ value); could you do this?
window.open('ITEM.PRO?id='+ value.split(' ').pop());
There are a few different ways to acheive this.
This simplest is to add
value = value.slice(-5);
right before
window.open('ITEM.PRO?id='+ value);
This sets value to its last 5 characters. Read here about the String.slice function.
If you want set the value to the last 'word', so to speak, delimited by spaces, you could do this instead:
value = value.split(" ").pop();
Another method would be to take the last continuous string of digits in the value. For that, you could use this:
value = value.match(/\d+/).pop();
Which method you use, of course, depends on what would work most reliably with the input you have.
Try this
var onAutocompleteSelect = function(value, data) {
window.open('ITEM.PRO?id='+ value.substring(value.length-5));
}
This is a terrible solution, but will work in the case you listed. I will edit if you post more details:
<script type="text/javascript">
var options, a;
jQuery(function(){
var onAutocompleteSelect = function(value, data) {
window.open('ITEM.PRO?id='+ value.match(/\d+/)[0]);
}
options = {
serviceUrl:'JQUERY-SEARCH.pro',
onSelect: onAutocompleteSelect,
};
a = $('#query').autocomplete(options);
});
</script>
value.match(/\d+/)[0] will match any digits in your string as any array, so we take the first item in that array.
When your IDs exceed 5 digits, your code will break (as has been stated in comments). You can also use the .split approach mentioned by #bordoz, the disadvantage being that spaces in any of the other words would break this solution. Or you could use:
var url = 'ITEM.PRO?id='+ value.replace(/[^\d\.]/g,'');
Which would fail only if any of the other word contain numbers. Which one best fits your situation?

Find the first character of input in a textbox

I am stuck in implementing the following:
User starts typing in a textbox.
The javascript on page captures the first character typed, validates that it is an english alphabet (a-z,A-Z) and converts it to lowercase (if necessary).
Make an XMLHttp request based on the input (i.e. if first input character is a, get a.xml, if b get b.xml and so on).
I know how to do the last part (make the xmlhttp request) but am kind of stuck on how to capture the first character and validate it (in a way that works on all browsers). Please guide. Thanks.
Clarification: This is to create a Google Suggest like autocomplete-drop-down menu without the need for server side programs.
Something like this should work:
HTML:
<input type="text" id="myField" />
And in JS:
window.onload = function() {
document.getElementById('myField').onkeyup = function() {
// Validate that the first letter is A-Za-z and capture it
var letter = this.value.match(/^([A-Za-z])/);
// If a letter was found
if(letter !== null) {
// Change it to lowercase and update the value
letter = letter[0].toLowerCase();
this.value = letter + this.value.substring(1);
// Do the request
}
}
}
My vanilla-JS skills are a bit rusty but this should do the trick. Just for the heck of it, here's the same using jQuery:
$(function() {
$('#myField').keyup(function() {
var letter = $(this).val().match(/^([A-Za-z])/);
// If a letter was found
if(letter !== null) {
// Change it to lowercase and update the value
letter = letter[0].toLowerCase();
$(this).val(letter + $(this).val().substring(1);
// Do the request
}
});
});
What part of the problem do you not know how to do? Here's an approach that you can follow. Very likely to need adjustments, but a good starting point
if our text field's id is 'txt'
document.getElementByID('txt').onkeypress = function(e) {
var textInField = this.value;
if (textInField.length == 1) {
var firstChar = textInField.charAt(0);
if (/[a-zA-Z]/.test(firstChar)) {
sendXHR(textInField.value.toLowerCase())
}
} else {
// What do you do if there is one or more chars???
}
}
Note that the other answers here mention onchange, that doesn't fire until the focus leaves the field, which I don't think is what you want

Categories

Resources