I have a page, showlist.php, which loads a set of results from a recordset. There is a search field which returns results using jquery load. This works fine for one word, but not if there is more than one word in the search query. Can anybody show how to get this to work for any search query? Must be some basic error but googling around has not helped.
Key elements of showlist.php:-
<div id="contentarea">
<script type="text/javascript">
function contentloader(url){
$("#contentarea").load(url);
}
</script>
<input name="search" type="text" id="inputsearch"/>
<a onclick="contentloader('showlist.php?search='+document.getElementById('inputsearch').value+'')">Search</a>
</div>
You need to HTML encode the result of document.getElementById('inputsearch').value so that all the works are passes to the server.
See:
HTML-encoding lost when attribute read from input field
Encode URL in JavaScript?
and links therein.
You need to call encodeURIComponent with the value to correctly format the query/search term:
<a onclick="contentloader('showlist.php?search='+encodeURIComponent(document.getElementById('inputsearch').value)+'')">Search</a>
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
type abc%20xyz in the box. if that works, maybe you need to urlencode the value.
You can use onClick listener, since you are already using jQuery. I think it is a better than using onClick attribute.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<div id="contentarea">
<input name="search" type="text" id="inputsearch"/>
<a id="search">Search</a>
<script type="text/javascript">
$( document ).ready(function (){ // when document ready
$("#search").click(function(){ // add a click listner
$("#contentarea").load(
encodeURI($('#inputsearch').val()) // encode input string
);
}
);
})
</script>
</div>
Related
This question already has answers here:
val() vs. text() for textarea
(2 answers)
Closed 4 years ago.
Not a duplicate question; so please consider the content closely before presumption.
I've been using JQuery for years and have never seen this type of behavior before. Consider the following:
<html>
<div class="order-form-group">
<label class="order-form-label" for="guestSpecialInstructions">Special Instructions:</label>
<textarea class="order-form-textarea" id="guestSpecialInstructions" type="text"></textarea>
</div>
<div class="order-form-group">
<label class="order-form-label" for="guestReason">Reason:</label>
<textarea class="order-form-textarea" id="guestReason" type="text"></textarea>
</div>
<div class="button-container">
<input class="order-form-submit" type="submit" value="Submit">
</div>
</html>
I've observed that the following script in some instances will return 'undefined' even when "all" the more obvious reasons have been eliminated. Such as
having the incorrect selector, having more than 1 id on the page and etc.
<script>
var specInstr = $("#guestSpecialInstructions").val();
var guestReason = $("#guestReason").val();
</script>
I spent literally hours attempting to determine what the disconnect was; stripping my code to the simplest basic level and couldn't find any reasonable explanation for the behavior.
The code is contained within a simple HTML page; nothing fancy and references the JQuery repository https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
I have another project which runs in an aspx page, still the markup is identical and the .val() method works without issue.
After hours of hitting a wall I ran across the post at JQuery: .val() is not working for textarea and someone else attesting to the exact same issue using valid code and the suggestion was:
<script>
var specInstr = $("#guestSpecialInstructions")[0].value;
var guestReason = $("#guestReason")[0].value;
</script>
Then the issue is automagically resolved. Only problem I have with this is that there no one seems to have answered the question of why the JQuery .text() method sometimes return undefined when all aspects of the code is valid.
Resolutions are great but without understanding why the issue exists, really gains nothing intellectually.
If I need to change the wording of the title, let me know.
You can only use text() on a <textarea> if it is pre-populated and to return the original content
Any changes to the content by user or setting new value programatically will not alter what is returned by text() as it will always be the original pre-pre-populated content
Always use val() to get and set
var $txt = $('textarea')
console.log('text() Original content:', $txt.text())
console.log('val() Original content:', $txt.val())
$txt.val( 'Some new content')
console.log('text() after value change:', $txt.text())
console.log('val() after value change:', $txt.val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="one" type="text">
Original text
</textarea>
I want to search multiple HTML files from a separate page, where I search for text from all the divs which has a specific id for each, whole id containing matched search term will be displayed on the search page in list.
The div list looks like this :
<body>
<div class='vs'>
<div id='header 1'>content 1 here </div>
<div id='header 2'>another text </div>
<div id='header 3'>whatever </div>
</div>
</body>
Please note that I want to perform search from different page and want to display results there with links to the searchable page.
For now I was searching like this :
HTML
<body>
<input type="text" id='search' />
<div class='vs'>
<div id='header 1'>content 1 here </div>
<div id='header 2'>another text </div>
<div id='header 3'>whatever </div>
</div>
</body>
JavaScript
$('#search').on('input', function () {
var text = $(this).val();
$('.vs div').show();
$('.vs div:not(:contains(' + text + '))').hide();
});
It is working on the fiddle here, but I don't want it to work like this, I want to do the search from a separate page remotely and display results there with link to this page.
Solution with jQuery and AJAX:
<form id="searchForm">
<input type="text" id="search"/>
<input type="submit" name="Search!" />
</form>
<div id="resultContainer">
</div>
<script type="text/javascript">
$("#searchForm").submit(function(e) {
e.preventDefault();
var results = $("#resultContainer");
var text = $("#search").val();
results.empty();
$.get("http://example.com/", function(data) {
results.append($(data).find("div:contains(" + text + ")"));
});
});
</script>
Fiddle (This fiddle enables you to search for content on the jsfiddle page, try for example JSFiddle as search term.)
Note however that this does not work cross-domain, because browsers will prevent cross-site scripting. You didn't describe your use-case clear enough for me to know whether you're okay with that.
You'll want to look at using PHP file_get_contents to retrieve the HTML contents of the external page, and from there analyze the data in the <div>s that you are interested in. Ultimately, you'll want to store each individual search term in a JavaScript array (you can create JavaScript arrays dynamically using PHP), and then create search functionality similar to example you posted to search all the elements in your array.
So on page load, you'll want to have a <div> in which you are going to list all the elements from the array. You can list these by looping through the array and displaying each individual element. From there, you will want to call a function every time the user enters or deletes a character in the <input> box. This function will update the <div> with an updated list of elements that match the string in the <input> box.
This is the theory behind what you are trying to accomplish. Hopefully it will give you some direction as to how to write your code.
Update:
If you're looking for a JavaScript only solution, check out a JavaScript equivalent of PHP's file_get_contents: http://phpjs.org/functions/file_get_contents/
From here, you can maybe look at using .split to break up the list. Ultimately, you're still trying to store each individual search term as an element in an array, it's just the method that you retrieve these terms is different (JavaScript as opposed to PHP).
Perhaps I was emphasizing too much on PHP, perhaps it's because it's the web development language I'm most familiar with. Hope this JavaScript-only solution is helpful.
I am working with a api where i need to post a url from a form and get response. Everything is working well except one thing. I could not figure out how to get url posted in form input in to a variable for javascript. Take a look at following.
<form action="#" method="post">
<input type="text" class="url" name="url" />
<input type="submit" value="Analyse for Page Speed" value="submit" />
</form>
I use above form to get url and i want that url to be a value for the following variable
// Specify the URL you want PageSpeed results for here:
var URL_TO_GET_RESULTS_FOR = 'your url here';
How to get this done?
Is this what you're looking for?
var URL_TO_GET_RESULTS_FOR = document.getElementsByName('url')[0].value;
getElementsByName returns an array with all elements having the name passed as parameter. Since I'm assuming you have only one element with name="url", I get the first position of the array and returns the value.
As #crush pointed out in the comments, this task alone probably does not merit the use of jQuery. So if you aren't already using it, this should probably not be the deciding factor. If you need a pure JS solution, go with #ClaudioRedi's answer.
However, I'm assuming you're already using jQuery, and are asking for a jQuery solution. So here it is:
var URL_TO_GET_RESULTS_FOR = $('form input[name="url"]').val();
This will get the value of an <input> with the name url within a <form> element.
I'm trying to take user form input and display it back to the user, among other things (all of which require the input being stored as a JS variable).
I'm trying to spit it out in an alert, as a quick feedback loop, and all I keep getting is [object HTMLInputElement]. I've tried to use document.forms[0] and document.getElementById (like below) and neither work. Also, I'm using bootstrap typeahead, could that be complicating this issue?
What am I missing?
Here's the code:
<div class="hero-unit">
<h1> Title </h1>
<p> This form description </p>
<form class="well" name="formInput" action= "#">
<label>Input</label>
<input Id="txtvarInput" class="span3" style="margin: 0pt auto;" type="text" placeholder="AAA, BBB, CCC..." data-provide="typeahead" data-items="10" data-source="["AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH","III","JJJ","KKK","LLL"]"/>
</label>
<div class="form-actions" "span3">
<input name="submit" type="submit" class="btn" value="Select" onclick="alert('you chose ' + theInput.value)"/>
<script language="JavaScript" type="Text/JavaScript">
var theInput = document.getElementById('txtvarInput');
</script>
</div>
</form>
</div>
<div class="page-header">
<h1>Input:
<script language="JavaScript" type="Text/JavaScript">
document.write(theInput.value);
</script>
</h1>
Edit: PART II, now the code works for the alert, but I need to use it elsewhere (like I said) and the variable isn't available in other sections of the html. Above, I'm just trying to get it to display that same value as a part of the html. It could be my JS, but this is pretty boilerplate stuff, so I think it's related to the location of the variable.
What do I need to do use it elsewhere? I've added the next div above to show what I'm trying.
--left an extra declaration of the variable in part II by accident, was one of the tests I was trying, removed now.
Right now, the object you're alerting is an HTML element, not a string. You can get its value using the value property:
alert('you chose ' + theInput.value)
(Note that you probably didn't mean:
var theInput = document.getElementById('txtvarInput').value;
As other answers suggest, because that would give you an empty string. It's only read once.)
You are trying to output the entire HTML-object that you have selected, not the value-property of it. Since alert() expect a string, JavaScript gives you the string representation of that object which is [object HTMLInputElement].
Try this instead:
var theInput = document.getElementById('txtvarInput').value;
var theInput = document.getElementById('txtvarInput');
should be
var theInput = document.getElementById('txtvarInput').value;
In the alert, use
theInput.value
You need to use the value property:
var theInput = document.getElementById('txtvarInput').value;
You forgot .value
Something like:
document.getElementById('txtvarInput').value
You are going to print the value of the input at the page load time. You will get an empty alert.
just do this!
<input name="submit" type="submit" class="btn" value="Select" onclick="alertVal()"/>
<script language="JavaScript" type="Text/JavaScript">
function alertVal(){
var theInput = document.getElementById('txtvarInput').value;
alert('you chose ' + theInput);
}
</script>
This is probably very simple, but could somebody tell me how to get the cursor blinking on a text box on page load?
Set focus on the first text field:
$("input:text:visible:first").focus();
This also does the first text field, but you can change the [0] to another index:
$('input[#type="text"]')[0].focus();
Or, you can use the ID:
$("#someTextBox").focus();
You can use HTML5 autofocus for this. You don't need jQuery or other JavaScript.
<input type="text" name="some_field" autofocus>
Note this will not work on IE9 and lower.
Sure:
<head>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#myTextBox").focus();
});
</script>
</head>
<body>
<input type="text" id="myTextBox">
</body>
Why is everybody using jQuery for something simple as this.
<body OnLoad="document.myform.mytextfield.focus();">
Think about your user interface before you do this. I assume (though none of the answers has said so) that you'll be doing this when the document loads using jQuery's ready() function. If a user has already focussed on a different element before the document has loaded (which is perfectly possible) then it's extremely irritating for them to have the focus stolen away.
You could check for this by adding onfocus attributes in each of your <input> elements to record whether the user has already focussed on a form field and then not stealing the focus if they have:
var anyFieldReceivedFocus = false;
function fieldReceivedFocus() {
anyFieldReceivedFocus = true;
}
function focusFirstField() {
if (!anyFieldReceivedFocus) {
// Do jQuery focus stuff
}
}
<input type="text" onfocus="fieldReceivedFocus()" name="one">
<input type="text" onfocus="fieldReceivedFocus()" name="two">
HTML:
<input id="search" size="10" />
jQuery:
$("#search").focus();
Sorry for bumping an old question. I found this via google.
Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.
eg.
$('#myform input,#myform textarea').first().focus();
This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.
This is what I prefer to use:
<script type="text/javascript">
$(document).ready(function () {
$("#fieldID").focus();
});
</script>
place after input
<script type="text/javascript">document.formname.inputname.focus();</script>
The line $('#myTextBox').focus() alone won't put the cursor in the text box, instead use:
$('#myTextBox:text:visible:first').focus();
$("#search").focus();
You can also use HTML5 element <autofocus>
The Simple and easiest way to achieve this
$('#button').on('click', function () {
$('.form-group input[type="text"]').attr('autofocus', 'true');
});