javascript getting the value of a text box - javascript

I have this text box here...
<input name="search" type="text" maxlength="512" id="search" class="searchField" autocomplete="off" title="" />
and I also have this submit
<input type="submit" name="btnSearch" value="Search" onclick="location.href='http://www.website.com/search/';" id="btnSearch" class="buttonSearch" />
what I am trying to do is add whatever is in the text box in my
onclick="location.href='http://www.website.com/search/';"
so it would look like this..
onclick="location.href='http://www.website.com/search/what ever the user searches';"
how would I go about doing this, I have been googling my little heart out.

Please avoid mixing JavaScript and HTML. You can remove onclick attribute and replace it with this in plain JavaScript somewhere after the DOM has loaded:
document.getElementById('btnSearch').onclick = function() {
var search = document.getElementById('search').value;
var searchEncoded = encodeURIComponent(search);
window.location.url = "http://www.website.com/search/" + searchEncoded;
}
Also remember about escaping the search box, e.g. using encodeURIComponent(). Here is a working jsfiddle example.

This should work:
onclick="location.href='http://www.website.com/search/'+document.getElementById('search').value;"
But I wouldn't ever write that in one of my project as writing script directly on tags is a bad practice.

Here is a working jsfiddle
I moved the event handler out of the button as it is more maintainable. Also I encode the search query so that it gets to the server properly.
var search = document.getElementById('search');
var submit = document.getElementById('btnSearch');
submit.addEventListener('click', function(e) {
var searchValue = encodeURIComponent(search.value); // encode the search query
window.location.href = 'http://www.website.com/search/' + searchValue ;
});

You can add it to the onclick event like so
document.getEelementById("btnSearch").onclick = function(){
location.href='http://www.website.com/search/' + document.getEelementById("search").value;
}
edit: aaaaand too slow... oh well. At least this is not inline.

You would be better off using the < script> tag for this task. Example:
<input name="search" type="text" maxlength="512" id="search" class="searchField" autocomplete="off" title="" />
...
<input type="submit" name="btnSearch" value="Search" id="btnSearch" class="buttonSearch" />
<script type="text/javascript">
var button= document.getElementById('btnSearch');
button.onclick= function(){
var text= document.getElementById('search').value;
location.href='http://www.website.com/search/'+text;
}
</script>
However, you should try to 'clean' a little the text from the textbox so when you append it to the url you get a valid url. You should trim the text, then search for special characters and escape them, etc.

Related

Button search and function

I have filter/search here. But the search is when I'm insert the value and get ENTER it success. Right now, I want to change the search with button search and textarea for input the value. It is supposed to have like that. Do I need to add search button? Please see my demo below, thank you.
DEMO
I have done this
I want to change to this
HTML
<input id="text" type="text" class="k-textbox" placeholder="Search by name" />
JavaScript
$('#text').change(function(e){
var grid = $('#grid').data('kendoGrid');
var field = 'ProductName';
var operator = 'contains';
var value = this.value;
grid.dataSource.filter({
field: field,
operator: operator,
value: value
});
});
});
Add a button
<input type="button" id="btnSearch" value="Search" />
Change this
$('#text').change(function(e){
to this
$('#btnSearch').click(function(e){

jQuery/Javascript - Get value of text input field, and display in div

I am testing getting a text input, and printing the result in a div below. However, I can't see to get it to work.
If the "placeholder" of the input field to a "value", it inexplicably works. I may just be tired, and missing something obvious, but I can't for the life of me work out what's wrong.
//Tested and didn't work
//var URL = document.getElementById("download")[0].value;
//var URL = document.getElementsByName("download")[0].value;
var URL = $('#download').val();
function downloadURL() {
//Print to div
document.getElementById("output").innerHTML = URL;
//Test, just in case innerHTML wasn't working
alert(URL);
}
<p><input type="text" name="download" id="download" placeholder="Download URL"></p>
<button onclick="downloadURL()">Test</button>
<div id="output"></div>
Just a small change, you have to get value when you click on button, so first save a reference to that field and then get value when required
var URL = $('#download');
function downloadURL(){
//Print to div
document.getElementById("output").innerHTML = URL.val();
// alert(URL.val());
}
If you want to go jQuery...
var URL = $('#download');
function downloadURL() {
$("#output").html(URL.val());
}
... or plain JavaScript
var URL = document.getElementById("download") ;
function downloadURL() {
document.getElementById("output").innerHTML = URL.value;
}
I'd recommend you to stick with jQuery. Let jQuery behave in an unobtrusive way instead of relying on an inline event handler attached to the button.
<p> <input type="text" name="download" id="download" placeholder="Download URL"></p>
<button>Test</button> //remove the inline click handler
<div id="output"></div>
$('button').on('click', function() {
var url = $('#download').val();
$('#output').text(url); //or append(), or html(). See the documentation for further information
});
Minor modifications on your code so that it can be aligned to "Unobtrusive Javascript".
HTML
<p>
<input type="text" name="download" id="download" placeholder="Download URL">
</p>
<button id="btnDownloadUrl">Test</button>
<div id="output"></div>
jQuery
$(function(){
$("#btnDownloadUrl").bind("click", function(){
var downloadUrl = $("#download").val();
$("#output").html(downloadUrl);
});
});

clear text box using JS function in a href on click

I have this function:
<script>
function ClearTextBox(textbox_name) {
$(textbox_name).val("")
}
</script>
that removes values from a text input
i am trying to call it using:
Clear
but its not clearing the text box
You should use Unobtrusive JavaScript .
Try this code.
$('a').on('click',function(){
$('#customercompany1').val("");
});
It seems working fine for me.. but the console shows the following error
Uncaught SyntaxError: Unexpected token )
this is due to the javascript:void(); in your href attribute.
so i changed the mark up to
Clear
<input type="text" id="customercompany1" value="test value" />
and the script as
function ClearTextBox(textboxname) {
$(textboxname).val(" ");
return false;
}
Hope this helps....
DEMO HERE
Write your function like this:
function ClearTextBox(myInput) {
var txtBox = document.getElementById(myInput);
txtBox.value = "";
return false;
}
And write your html like this:
Clear
<input type="text" id="customercompany1" />
Need to see your HTML to be sure, but I'm guessing your text box looks like this :
<input type="text" name="customercompany1"/>
and it needs to look like this :
<input type="text" name="customercompany1" id="customercompany1"/>
The '#' jQuery selector matches on the id attribute, not the name attribute.
(This is true if you have used a textarea rather than an input)

Textarea realtime update by multiple input values

This is my form example:
<form action="" method="POST">
<input type="text" name="firstTarget" />
<input type="text" name="secondTarget" />
<input type="text" name="thirdTarget" />
<textarea name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
</form>
I want to update my textarea value in realtime by replacing the words firstTarget, secondTarget and thirdTarget with the actual values from firstTarget, secondTarget and thirdTarget inputs.
You can do something like this:
/* cache original value so we keep the keywords*/
var txt=$('textarea').val();
$('input').keyup(function(){
var newText=txt;
newText=newText.replace( this.name, this.value);
$('textarea').val(newText);
});
One issue however is if textarea is not set as readonly and user changes anything within it this won't work as it relies on storing the original value and changing that. Would need to know more about use case for this setup to help advance it further.
Same issue exists in other solutions as well if user touches any of the keywords all will fail
DEMO
Here's a solution that stores the input value on every keyup so textarea can be edited by user as well.
$('input').keyup(function(){
/* value to be replaced is stored in data object*/
var regVal=$(this).data('replace');
var newText=$('textarea').val().replace( regVal, this.value);
/* store value that will get replaced*/
$(this).data('replace', this.value)
$('textarea').val(newText);
}).each(function(){
/* on page load set initial replacement value as name of input*/
$(this).data('replace', this.name);
});
Only limitation is it assumes no duplicate entries by user
DEMO
HTML:
<form action="" method="POST">
<input type="text" name="firstTarget" onblur="tst(this);" />
<input type="text" name="secondTarget" onblur="tst(this);" />
<input type="text" name="thirdTarget" onblur="tst(this);" />
<textarea style="width:500px; height: 100px;" name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
</form>
And javascript:
function tst(elm){
var trgt=document.getElementsByTagName('textarea')[0];
trgt.value=trgt.value.replace(elm.getAttribute('name'), elm.value);
}
Working jsfiddle demo here
EDIT:
should you want to update multple instances of your needles like firstTarget, then you need to create the regex on the fly so you can pass it the global flag.
function tst(elm){
var trgt=document.getElementsByTagName('textarea')[0];
trgt.value=trgt.value.replace(RegExp(elm.getAttribute('name'), 'g'), elm.value);
}
Working jsfiddle demo here
you can use this code to do it:
$('firstTarget').onChange(function(){
var str = $('result').val();
str.replace(firstTarger, $( this ).attr('name'));
$('result').text(str);
}):
$('secondTarget').onChange(function(){
var str = $('result').val();
str.replace(firstTarger, $( this ).attr('name'));
$('result').text(str);
}):
$('thirdTarget').onChange(function(){
var str = $('result').val();
str.replace(firstTarger, $( this ).attr('name'));
$('result').text(str);
}):
enjoy!!!

Set the default value of an input text

my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field

Categories

Resources