I've got a textbox, and I want to select a substring programatically. Is there an easy way to do this?
To highlight the selected text in the textbox, you can use this javascript snippet:
var textbox = document.getElementById("mytextbox");
if (textbox.createTextRange) {
var oRange = this.textbox.createTextRange();
oRange.moveStart("character", start);
oRange.moveEnd("character", length - this.textbox.value.length);
oRange.select();
} else if (this.textbox.setSelectionRange) {
textbox.setSelectionRange(start, length);
}
textbox.focus();
In this snippet, mytextbox is the id the input textbox and start and length represent your substring parameters.
My JS is a little rusty, but something along the lines of:
document.getElementById("foo").value.substring(start, end);
should get you started.
And, I'm assuming that you're referring to a <textarea>.
<input type="text" id="textbox" value="sometextintextbox" />
<script type="text/javascript">
var textboxvalue=document.getElementById("textbox").value;
alert(textboxvalue.substring(3,7));
</script>
Related
I have been looking for way how I could filter data within textarea using regex function for a quite a while now without any success. Below is the regex I want to use to filter UK telephone numbers.
(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?
Fiddle: https://jsfiddle.net/qdypo04y/
I want to achieve the result when the button is clicked it will remove lines which do not meet the regex? Alternatively would remove values which are not UK telephone numbers.
Any guidance would be appreciated.
Apart the use of textarea element your issue is:
how attach click event listener to your button (refer to: querySelector and addEventListener)
how get the content of textarea and split it into rows (refer to: textContent plus split and join)
finally how use your regex: refer to test
An example is:
document.querySelector('button').addEventListener('click', function(e) {
var txtArea = document.querySelector('textarea[rows="4"][cols="50"]');
var re = /(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?/;
var txtArr = txtArea.textContent.split('\n');
txtArr.forEach(function(ele, idx) {
txtArr[idx] = ele + ' test result is: ' + re.test(ele);
});
txtArea.textContent = txtArr.join('\n');
});
<textarea rows="4" cols="50">
+447222555555
0800 042 0213
2017/07/14
2017/07/17
2017/07/27
</textarea>
<button>Click me</button>
<script>
function myFunction() {
var regexp = /(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?/;
var content=$.trim($("textarea").val()).split('\n');
var result="";
for(var i = 0;i < content.length;i++){
if(regexp.test(content[i])){
result=result+content[i]+'\n';
}
}
$("textarea").val(result);
}
</script>
used JQuery to take the value from textarea
I am trying to replace a string value in textarea while typing in textbox with jquery. I used keypress event to try achieving that. What may be the issue here in this fiddle?
<input type="text" id="textbox" />
<textarea id="txtArea">This is a sample test.</textarea>
jquery code
$("#textbox").keypress(function () {
var txtAreaValue = $('#txtArea').val();
var txtAreaValueAfterreplace = txtAreaValue.replace('sample', $(this).val());
$('#txtArea').val(txtAreaValueAfterreplace);
});
The main problem is that, when using keypress you are getting the value of the input box before it is set, so nothing appears. However even if you change it to keyup you still will only get one value because once 'sample' is replaced it is gone so therefor it cannot be replaced again.
A new logic needs to be considered if you are wanting to replace sample with the full value of the textarea. Consider the following example:
$("#add").click( function () {
$( '#txtArea' ).val( $('#txtArea').val().replace( 'sample', $("#textbox").val() ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" /><br>
<input type='button' id='add' value='add'>
<textarea id="txtArea">This is a sample test.</textarea>
Or we replace when the user stopped typing
var typing;
$("#textbox").keyup( function () {
// Stop the change from being made since they typed again
clearTimeout(typing);
// They typed, so set the change to queue up in a 3rd of a second
typing = setTimeout(function(){
$( '#txtArea' ).val( $('#txtArea').val().replace( 'sample', $("#textbox").val() ) );
},350);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" /><br>
<textarea id="txtArea">This is a sample test.</textarea>
You want to look for keyup, not keypress (you want to make sure you get the whole string.
You are trying to put the textbox value right? You're looking for the textarea value in line two of the javascript.
If you replace sample on the first key stroke, there won't be anything to replace the second key stroke.
You can simplify lines 3 and 4 into one line.
replace can only be used on a string. So you need to get the value first, if you're going to do it that way. txtAreaValue.val().replace('sample', $(this).val());
Feel free to play around with it on this fiddle: http://jsfiddle.net/snlacks/abc6skp9/
$("#txtBox").on('keyup', function () {
var txtValue = $(this).val();
$('#txtArea').val("this is a " + txtValue);
});
If you have a longer string, replace might work better, but you still need to store the full string somewhere.
var longString = "some really long string... sample... more...";
$("#txtBox").on('keyup', function () {
var txtValue = $(this).val();
$('#txtArea').val(longString.replace('sample', txtValue);
});
I have a list of URLs:
localhost/action/add/234
localhost/action/add/244
localhost/action/add/334
localhost/action/add/254
In front of these values there is a text box, and when a value is typed into the box I want to append it to the end of the URL.
localhost/action/add/234/test text1
localhost/action/add/244/test text2
localhost/action/add/334/test text3
localhost/action/add/254/test text4
Can someone explain me how can I do it? I found out that its possible to do it using .val() but I'm unsure how to use it.
If you want it to update immediately:
<script>
$(function(){
var a = $('#url').text();
$('#textbox').keyup(function(){
var b = $('#textbox').val();
$('#url').text(a + '/test ' + b);
$('#url').attr('href', a + '/test ' + b);
});
});
</script>
<input id='textbox' type='text'></input>
<a href="localhost/action/add/234" id='url'>localhost/action/add/234</a>
The key things here are
use the .keyup() event to run the function whenever a keyboard key is released
modify the .text() of the url element on keyup
modify the 'href' attribute of the url element so that the link matches the text
Normally .val() is used to set/get the value of input elements, like the text box ^, or a dropdown
Assuming, you want to append the text that you typed in the textfield to the href (URL).
I think we can make it more simple.
Here is the working solution.
$(document).ready(function(){
$('#search').on('click', function(e) {
var search_url = e.originalEvent.currentTarget.href; //or else you can grab the URL anywhere from your DOM;
e.originalEvent.currentTarget.href = search_url + $('#search_term').val();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search_term" placeholder="Search..StackOverflow" />
Search
$(function(){
var currVal = $('.url').text();
$('input[type="text"]').keydown(function() {
$('.url').text(currVal.trim()+$(this).val().trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="url">
localhost/action/add/234
</span>
<input type="text" id="search_term" placeholder="blabla" />
i'm making a little smiley script for my site and i wonder how do i use jquery/javascript to find ::id:: inside a sentence inside an input box(text).
Example:
I have typed ::123:: into my text box and when i click enter jquery will find for it and get the id out of it which is 123 , then turn it into an image.
<input id="tb" type="text" value=""></input><input id="btn" type="submit" value="Send"></input>
<div id="display">
image will be displayed here
<img src="...domain/image?id=123">
</div>
jQuery:
var inputval = $('#tb').val();
$(document).ready(function(){
$('#btn').click(function(){
//get the id from inputval(variable)
});
});
P/S it will also check for if it's intergar.
Use String.replace with a regex and group reference:
var strWithImgs = inputval.replace(/::(\d+)::/g, "<img src='...domain/image?id=$1'>")
$("#display").html(strWithImgs);
The $1 means "the first expression in parentheses", which is the run of digits.
You could do
$('#tb').keyup(function(e){
if(e.which === 13){
var value = this.value.replace(/::/g, '');
if(jQuery.isNumeric( value )){
$(this).next().find('img').attr('src' , "...domain/image?id="+value)
}
}
});
this means thatif the user press return the value inside the textfield will be parsed, and after removing the ::, if it's a number will be used for the src of the img
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/