find and change ::123:: text inside a textbox into an image - javascript

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

Related

Get the value of an <input type="text"> that was created dynamically inside a modal

i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment".
This is how i make the input:
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
$("div.modal-body").append(p);
The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.
1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val()
2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />");
$("body").append(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Not really the answer here, but might help you get at the root of the problem.
JS:
var newComment, defaultValue;
function doOnBlur(){
newComment = $('#comment_text').val()
}
function doOnFocus(){
if($('#comment_text').val() == defaultValue){
$('#comment_text').val('')
}
}
HTML:
<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' />
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->
from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML

Jquery replace string in a 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);
});

Linking form and button to javascript command

I am trying to make a simple form and button work. I have linked to a JS Fiddle here View JS Fiddle here
<form>
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button type="submit" id="WFFsearch">Search</button>
</form>
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').text();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
I want to be able to enter "nba" without the quotation marks and click the search button, then have a new window which generates the following link http://espn.go.com/nba/statistics. The first part and the last part of all the urls will be the same, it's just the middle that changes (nba, nfl, mlb). Any help would be greatly appreciated, thanks!
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
You need val() property, since input is in question, not text(). https://jsfiddle.net/1c93pqj0/2/
you wanna use the .val() instead of .text() as text gets the value between 2 tags <div>here is some text</div> and val gets the value <input value="some value"/>
EzPz! This is a very simple task. First of all though, since you're using jQ to establish your button's click event, you can either drop the attribute type="submit", OR (recommended), create your event on the form's submit. If it were me, I'd id the form and use the forms submit, so that you don't need any alters to your button type="submit" and enter key can still be used in search box to submit the form.
Also, you're trying to .text on an input. Input's have value. In jQuery you can get or set that value by calling .val() instead.
The code:
$('#frmGetStats').on('submit', function (e) {
e.preventDefault();
var searchInput = $('#search').val(),
url = "http://espn.go.com/" + searchInput + "/statistics",
win = window.open(url);
alert("In this sandbox, new windows don't work. \nHowever you can see the link is \n[" + url + "]");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="frmGetStats">
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button id="WFFsearch" type="submit">Search</button>
</form>
To get the value of an input field, use .val(). .text() is for the text in a DOM element.
Clicking on the submit button submits the form by default, which reloads the page and kills the script. You need to return false from the event handler to prevent this.
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
return false;
});
DEMO

Taking a HTML form <input> value and using it to modify a <p> tag with Javascript

I am fairly new to Javascript and am trying to create a simple madlib application where a user can input a word through an HTML page and have that word appear in a paragraph tag when the user clicks the "submit" button. I am having troubles displaying the word that the user inputs. I know that I am close but for the life of me cannot figure out what I am missing.
Here is the HTML I am using:
<form>
<label>Word</label><input id="word"></input>
<input type="submit" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
And the Javascript:
var word = document.getElementById('word').innerHTML,
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
Here is a JSFiddle: https://jsfiddle.net/5c4j2opc/
I have made a new JSFiddle: https://jsfiddle.net/5c4j2opc/3/ which works.
I changed type="submit" to type="button" to stop the page refreshing when the button is clicked and moved the word variable to the replaceStory function so it doesn't just get called once at the beginning of the script! Hope this helps.
You have to change two things.
The first is you are using innerHTML in a input element, when you want to access input element you need to get the value not the innerHTML, inputs not have this property.
The second one is that you need to pass the event on the onclick event since if you don't do it you can't cancel the submit action and then the page will be submit it automatically and reload the content. Then after you pass the event you have to apply event.preventDefault which will stop the submit for that button. Other option to avoid this problem would be possible to replace the submit button with a <button> tag or <input type="button"> since not of them will trigger the submit action.
You can see a working example https://jsfiddle.net/5c4j2opc/9/
html -> same you have
javascript
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(e){
replaceStory(word.value);
e.preventDefault();
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
You initialize wordjust in the beginning of the script. Besides, that the input value is not innerHTML, during that time, the value is empty.
As long as the return value is not set explicitly to false, the form will reload the page and overwrite any result.
Change your code:
var originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
var word = document.getElementById('word').value;
replaceStory(word);
return false;
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
originalStory.innerHTML = story;
};
updated fiddle
You had a couple of minor problems. The input type of the submit button should be button rather than submit. Submit does a post request and refreshes the page with the data received.
Initially you had:
var word = document.getElementById('word').innerHTML this would get the initial innerHTML which would be nothing. You have to get the inner text within word every single time the button is clicked to get the most recent text inside the textbox.
Finally, for a input node you should get .value rather than .innerHTML to get the inner text
html:
<form>
<label>Word</label><input id="word"></input>
<input type="button" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
javascript:
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word.value);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
I advise you to just understand Javascript first, and after then, focus on learning Jquery because it's much more easier and handy.
By the way if you want to do what you said:
You shouldn't use form tag, because you don't want to send something to server-side and you can use div tag as well instead of form tag.
<div>
<label>Word</label>
<input id="word" type="text"></input>
<button id="submitButton">Submit</button>
</div>
<span>A </span><span id="text">{here}</span><span> is now part of the story</span>
Jquery
$('#submitButton').click(function(){
txt = $('#word').val()
$('#text').text(txt);
});
Don't forget to import Jquery Package.
https://jsfiddle.net/softiran/gt8rr5pe/
You could also allow the user to change your story directly. I know this may not use an input tag, but it was very useful to me.
<div id="story">Once upon a time there was a man named
<p id="added" contenteditable="true" title="Click to change">
Bill</p>. He liked to eat tacos.</div>
I used this in a code that changed the name of the main character of a story into a user-selected name and allowed them to download the story. Hope this helps! All the user has to do is click the name "Bill" and they will be able to change the name to anything they want.

Append text field value to URL using jQuery

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" />

Categories

Resources