I am trying to remove the literals in a phone number (999) 999-9999 to make it 9999999999 in another hidden input value.
Can this be accomplished using the .val() function or can you only add more values to the hidden input?
phone1= (999) 999-9999
phone should have this value= 9999999999
$('#phone1').bind('keypress blur', function() {
$('#phone').val($('#phone1').val() + ' ' );
});
get value
run string replace
set value
Basic idea with a plain string
var str = "(999) 999-9999 ";
var newStr = str.replace(/\D/g,"");
console.log(newStr);
Now the best way to write what you did would be
$('#phone1').on('blur', function() { //jQuery 1.7.2+ use on, not bind
var txtBox = $(this);
txtBox.val( txtBox.val().replace(/\D/g,"") );
});
You need the replace [MDN] method. It's what's going to do most of the work for you:
$('#phone').val($('#phone1').val().replace(/\D/g, ''));
The first parameter can be either a substring or a regular expression. In the example, I've used the regex for "not a digit".
$('#phone1').on('keypress blur', function() {
$('#phone').val(this.value.replace(/[^\d]/g, "") + ' ' );
});
FIDDLE
Related
Scenario :
After double quote,next characters were not displaying.
I know this is because of escaping of single and double quotes, I have tried this regex (/"/g,'\"'), but its not working.
Can someone help me review the code?My wanted output is that all characters on div should also display on input.
PS: I want to avoid replace(/"/g,'"') as much as possible.
<div>single ' double " single ' </div>
<form>
</form>
$("form").append('<input type="text" value = "' + $("div").text().replace(/"/g,'\"') + '" />');
see this Fiddle demo
Try this method (demo):
$('<input>', {
type: 'text',
value : $("div").text()
}).appendTo('form');
Update: for multiple elements, try this (demo)
var txt = $('div').text();
$('<tr><td><input type="button"></td><td><input type="text"></td></tr>')
.appendTo('table')
.find('input')
.val( txt );
Sorry for the noobish question but, I am trying to build a form summary that will populate a div (immediately) with all of the fields being used. Here is a small sample of the field: Fiddle
For some reason the JS is not working as I would expect it to, can anyone point out what I am doing wrong?
For example, I would like it to output: "AND name: john EXCEPT number 222".
I would also like to be able click on a result to remove it, and clear the field. Thank you
$(".allS").change(function () {
if ($(this).next('.textArea').not(':empty'))
// varible to hold string
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#text_here").text(str);
}).change();
$('.textArea').change(function(){
var $inputs = $('form#form :input[type="text"]'),
result = "";
$inputs.each(function(){
// access the individual input as jQuery object via $(this)
result += $(this).val()+"<br>";
});
// store result in some div
$('div#text_here').text(result);
}).change();
There were many mistakes in your code. I simplified it to a very short code that only does what's needed to get the output you requested. Here's the working fiddle.
$(".allS, .textArea").change(function () {
var str = '';
if ($('#name').val().length > 0 && $('#number').val().length > 0)
var str = $('#nameMod>option:selected').text() + ' name:' + $('#name').val() + ' ' + $('#numberMod>option:selected').text() + ' number ' + $('#number').val();
$("#text_here").html(str);
});
Basically, what this does is attach a change event handler to both classes (.alls, .textArea), and when the event is triggered, both input fields are tested for any content. If this test passes, a string is composed out of all the relevant values, and the div content is set. If the test failed (no content), the str variable contains an empty string and the div is cleared.
Just glancing at the code, the selector 'form#form :input[type="text"]' looks wrong. For starters, input is not a pseudoclass. Also, attribute matching shouldn't have the quotes.
This may or may not be what you want (I think it is, from looking at your html):
'form#form input[type=text]'
Also your <br>'s are not working because you called text(). call html() instead.
i have this this code:
$(document).ready(function(){
$("input").focus(function(){
$(this).css('outline-color','#559FFF');
$(this).blur(function(){
$(this).css("outline-color","#FF0000");
});
});
$("input").click(function(){
var value = $(this).val(function(){
$(this).html("");
});
});
$(".awesome").click(function(){
var toStore = $("input[name=name]").val();
if((toStore===/[a-zA-Z]/)===true){
$("#contain").children().fadeOut(1000);
$("#contain").delay(5000).queue(function(){
$("#contain").append("<p>welcome : " + toStore + " </p>");
});
}else{
alert("You Must Put a Valid Name");
}
});
});
i want my code to test and catch the value of my input and if the value is a characters
between a-z including capitalize with a space between two words like: "FirstName LastName"
if its ok thne procced to:
$("#contain").children().fadeOut(1000);
$("#contain").delay(5000).queue(function(){
$("#contain").append("<p>welcome : " + toStore + " </p>");
});
else alert the user that he must put valid characters.
I think this regex should work:
if (/^[A-Za-z]+ [A-Za-z]+$/.test(toStore)) {
}
and should be put in place of your if((toStore===/[a-zA-Z]/)===true){
DEMO: http://jsfiddle.net/tDVWk/
This checks that the input follows this:
Starts with 1 or more alphabetic characters (any can be uppercase or lowercase)
Contains a space after the previous set of characters
Ends with 1 or more alphabetic characters (any can be uppercase or lowercase)
If you want to be more strict and require that each name start with an uppercase letter and the rest be lowercase, you can use:
if (/^[A-Z][a-z]? [A-Z][a-z]?$/.test(toStore)) {
}
But that isn't ideal, as names are very different and could easily be something like "McLovin"...where this second example would definitely fail. Hopefully my first example should complete what you need.
Of course, there's always the debate that you shouldn't restrict something like this so much. What if their name is more than just a first and last? What if they have a suffix, like "III" (or actually "3"), designating they are the third of their family with that name? What if people want to include their middle name (on purpose or accident)? It might make more sense for you to use two textboxes for each name, making it more clear for the user. That way, all you have to do is validate that each is filled in (and maybe only has alphabetic characters). Then again, I'm not sure what your requirements are and what this textbox you already have is for :)
Something like this? You'll need to add your code where you need it.
<script>
function validateInput(obj, e){
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
var AllowRegex = /^[\ba-zA-Z,\s-\f\n\r\t\v]$/;
if (AllowRegex.test(character)){
return true;
}
else{
alert('!');
return false;
}
}
</script>
<input id="input1" onkeydown=" return validateInput(this,event) "/>
Here i have a textbox in which user inputs html tags like <h1>hello</h1> then i append that text to a td with
var text = $('textbox').val();
$('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');
Now what i want is the text in the td should come text as entered <h1>hello</h1> and not hello with h1 tag
I tried escape and unscape but it didnt helped
Used encode function from here HTML-encoding lost when attribute read from input field
function htmlEncode(value){
return $('<div/>').text(value).html();
}
var text = htmlEncode($('textbox').val());
$('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');
Here’s a plain JavaScript function without the jQuery overkill:
function htmlEncode(str) {
return str.replace(/[<>&"']/g, function($0) { return "&" + {"<":"lt",">":"gt","&":"amp",'"':"quot","'":"#39"}[$0] + ";"; });
}
This looks for any occurrence of <, >, &, ", and ', calls the function that then looks up the matched character and returns the corresponding character reference.
You could try replacing the < by < and > by >
var text = $('textbox').val();
text = text.replace(/</g,'<').replace(/>/g,'>');
$('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');
You can test it yourself here: http://jsfiddle.net/W7RWA/
You need to set the node value with the val() method:
// Untested
var text = $('textbox').val();
var tr = $('<tr><td style="padding:0px 12px;color:black"></td></tr>');
tr.find("td").val(text);
$('table').append(tr);
if you want html_entities ....
try the phpjs project
https://github.com/kvz/phpjs/blob/master/functions/strings/htmlentities.js
.. it also requires this function though https://github.com/kvz/phpjs/blob/master/functions/strings/get_html_translation_table.js
PHPJS is an excellent resource for these sorts of "How can I use this PHP function in Javascript?" questions.
Javascript htmlentities()
So I have a textbox which allows a max entry of 5 characters.
The user should enter the time in the format hh:mm or hhmm , into the textbox.
Supposing the user enters 1:2:3 or 1::2 etc, then it should show an alert message('Incorrect time format')
Is there any way I can check all other occurences of : EXCEPT for the first : , and alert the user?
(This needs to be done within a javascript function)
This is what I used to check for non-digit values(excluding :) entered into textbox:
<script type='text/javascript'>
function getClks(){
...
var re=":";
var found = clks.match(re);
if (clks.match(/^[0-9:]/)){
alert('Invalid time value');
}
if (found=:){
var splitime = clks.split(":");
var hours = splitime[0];
var mins = splitime[1];
......
}
}
</script>
Unless you have a very good reason to change the user's input. I would recommend only alerting the user that their input doesn't match the correct format.
If you really want to remove characters, you can use the replace function with some regex to remove the extra : chars.
You can use search or match to test whether the input is in the correct format.
Something like /^\d{1,2}:\d{2}$/ should work.
try to use this jquery plugin: http://digitalbush.com/projects/masked-input-plugin/
It will mask your textbox:
$("#hour").mask("99:99");
#alexl's jQuery plugin is probably enough, but for completeness sake..
Outside jQuery contexts I'd use a RegExp, /([0-9][0-9]):([0-9][0-9])/, and test the number string like so:
var timestr = /* .. get the text .. */
if(timestr.match(/([0-9][0-9]):([0-9][0-9])/) {
console.log('Good number string');
} else {
console.log('Bad number string');
}
Everyone else explained what to do. Here's a more concrete example of how to use it.
var regex = new RegExp("\\d{2}[:]\\d{2}");
if (regex.test(input)) {
var array = input.split(":");
var hours = array[0];
var minutes = array[1];
} else {
alert("malformed input");
}
You could do something like this
markup
<input id="myinput" maxlength="5" type="text" />
<input type="button" onclick="test()" value="test" id="testbtn" />
js
var re = new RegExp("^([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}$");
var myInput = document.getElementById('myinput');
function test(){
alert(re.test(myInput.value)); //alerts true if the input is well-formed
}
example => http://jsfiddle.net/steweb/rRZLx/