jquery - why code always takes old value of textbox? - javascript

I've a form with two textboxes for API Key and for stock ticker. Please find below the code.
<h1>Stock</h1>
<form id="frmGetComp">
<p>API Key: <input type="text" id="txtAPI" value="" /></p>
<p>Stock: <input type="text" id="txtStock" value="" /></p>
<p><button id="btnCall">Call</button></p>
</form>
And below is the jquery code:
$(document).ready(function () {
var stockId='';
$("#txtStock").blur(function () {
stockId= $(this).val();
console.log(stockId);
});
$('#btnCall').click(function () {
var apiKey = $('#txtAPI').val();
stockId= $("#txtStock").val();
console.log(':::call clicked:::', stockId);
<assigning apikey statement> = apiKey;
<stockId is passed in api call to fetch stock information>
$('#frmGetComp').submit(false);
$('#frmGetComp').reset = true;
stockId= '';
$('#txtStock').val('');
});
});
Now in this form when I enter information first time it retruns correct data. When I change the value of stock and click call button, every time it returns the stock information of first stock. It never takes new value entered in stock textbox.
How do I get new value of stock textbox and get the information of that stock when call button is clicked ???

Related

User input to build URL

I have a bit of experience with HTML but am very new to JavaScript. In essence, I would like for a user input to be part of a URL. For example, we could have something simple such as:
<script>
function get_cityname() {
var cityname = document.getElementById("cn").value;
alert(cityname);
}
</script>
<form>
Enter city name:
<input type = "text" size = "12" id = "cn">
<input type = "submit" onclick = "get_cityname();">
</form>
This will create a textbox where a user inputs their text (city name) and then click the 'submit' button next to it, and an alert should pop up based on the information they provided, just to make sure this works. However, this code only would seem to work (because of the 'onclick' command) to work for one user input. Therefore, I have 2 questions:
How could the above variable be included in a URL string? If it were something simple as:
URLstring = "https://sampleurl" + cityname + "moretext.html"
How could this be expanded if I want to include two or possibly even n number of inputs? For example, if I create more user prompt boxes and want to have the user also be able to input their zipcode, or state abbreviation, for example:
URLstring = "https://sampleurl" + cityname + "moretext" + zipcode + "moretext" + "stateabbreviation.html"
You could do something along these lines (it would be the same for one or more fields):
// Ensures the DOM (html) is loaded before trying to use the elements
window.addEventListener('DOMContentLoaded', function() {
var cnInput = document.getElementById("cn"),
zipInput = document.getElementById("zip"),
form = document.getElementById("myForm");
form.addEventListener('submit', getUrl); // On submit btn click, or pressing Enter
function getUrl(e) {
var cityname = cnInput.value,
zipcode = zipInput.value,
url = "https://sample.com/" + cityname + "/" + zipcode + ".html";
alert(url);
e.preventDefault(); // Prevent the form from redirecting?
}
});
<form id="myForm">
<label>Enter city name: <input type="text" size="12" id="cn"></label>
<label>Enter zip code: <input type="text" size="12" id="zip"></label>
<input type="submit">
</form>
First specify an action attribute for your form. This is where your form will be submitted. Then set your form's method attribute to GET. Finally, add as many fields as you like (I am assuming you are after a GET query such as https:url.com?key1=val1&key2=val2...):
<form method="GET" action="https://sampleurl">
Enter city name:
<input type="text" size="12" id="cn">
Enter zip code:
<input type="text" pattern="[0-9]{5}"
<input type="submit" ">
</form>

Passing the value of a button into a text field

I'm having some trouble with getting Javascript to pass a value (which is stored in local storage) into a textfield. Ideally, I'd like for someone to be able to click the 'apply here' button on one page, have the job number stored in local storage and then have it auto-populate the job number field on my application page with the job number.
This is what I've got so far, I have a feeling that I haven't assigned things correctly.
html (on submit page)
<p>
<form id="applyjob1" action="enquire.html" method="get">
<input type="submit" id="job1" value="Apply for Job" />
</form>
</p>
html (field I'm trying to put data into)
Job Reference Number <input required="required" id="jobNo" name="jobno" type="text" /> </br />
Javascript
window.onload = function init() {
var jobID = document.getElementById("job"); /*button name */
jobID.onsubmit = passJob; /*executes passJob function */
}
function passJob(){
var jobSubmit = localstorage.jobID("1984"); /*assigns localstorage*/
if (jobSubmit != undefined){
document.getElementById("jobNo").value = localstorage.jobID;
}
I think this code would work for your fuction.
function passJob(){
localStorage.setItem("jobID", "1984");
if (localStorage.jobID != undefined) {
document.getElementById("jobNo").value = localStorage.jobID;
}
}
You are assigning the jobSubmit wrongly. To set item, use localStorage.setItem('key', value). Note the casing as it matters.
So basically you should do
var jobSubmit = localStorage.setItem(,"jobID", "1984"); // assigns jobSubmit
And I don't see any element with id="job"

User inputted query for reddit search API

Now that I can utilize the search function for reddit's API, I want the user to input their own query. I'm new to javascript and I think the problem with my code is that the API search function is being ran before the user even inputs the query.
HTML:
<div id="site-content">
<form name="RedditSearch">
Enter your query:
<input type="text" name="query" onkeydown="if (event.keyCode == 13) document.getElementById('search').click()"/>
<input type="button" id="search" value="Search" onclick="searchquery();" />
</form>
</div>
Javascript:
var container = $('#site-content')
function searchquery()
{
var query = document.RedditSearch.query.value;
}
$.getJSON("http://www.reddit.com/search.json?q=" + query, function(data) {
$.each(data.data.children, function(i,item){
var title = item.data.title
var post = '<div>'+title+'</div>'
container.append(post)
});
});
Indeed, it appears that your getJSON query is executed when the page loads. At that time, the user hasn't input anything yet, so it is executed too early.
You need to add an event listener which will detect user input, and then perform the AJAX call to the reddit API.
Assuming your user inputs his keywords in a text area, you could use .change().
You can fine more informations here : http://api.jquery.com/category/events/‎ or here http://www.w3schools.com/jquery/event_change.asp
Example in your case : http://jsfiddle.net/2ECG6/1/

Setting the value of a parameter of a HTML form from a callback function

I have written this following piece of code with the help of different web sites. A snippet of the code is as follows:
function getLocation()
{
var visitorGeolocation = new geolocate(false, true, 'visitorGeolocation');
//Check for cookie and run a callback function to execute after geolocation is read either from cookie or IPInfoDB API
var callback = function()
{
var city=document.getElementById("city");
city.value = visitorGeolocation.getField('cityName');
alert('Visitor city name : ' + visitorGeolocation.getField('cityName'))
};
visitorGeolocation.checkcookie(callback);
}
</script>
</head>
<body onload="getLocation()">
<form name="frm" method="post" action="result.jsp?page=1">
<input type="text" name="myQuery">
<input name="city" id="city" type="hidden" value="city">
<input type="submit" name="submit" value="Submit">
</form>
I want to pass the value of city silently while submitting the form so that I can get the value of city in result page. That's why I set its type as "hidden". But I cannot understand how to set the value of city while submitting the form, because I get value of city in a callback function as shown above. I have no clue how to do this.
I am new to web programming. I have very little idea about callback function. So if anyone helps me to solve this I will be really grateful. Thank you.
I think that there is a dilemma because there is a
<input name="city" id="city" type="hidden" value="city"> with value=city
var city=document.getElementById("city");
city.value = visitorGeolocation.getField('cityName');
Then I suggest , remove value="city" inside <input name="city" id="city" type="hidden">, remove name="submit" value="Submit" or only name="submit" if you have to change the text's button.
Use this function :
function getLocation()
{
var visitorGeolocation = new geolocate(false, true, 'visitorGeolocation');
//Check for cookie and run a callback function to execute after geolocation is read either from cookie or IPInfoDB API
var callback = function()
{
document.getElementById("city").value = visitorGeolocation.getField('cityName');
alert('Visitor city name : ' + visitorGeolocation.getField('cityName'));
};
visitorGeolocation.checkcookie(callback);
}

Pass two values of input fields to script and combine for searching

In my current project, i have two text fields in which user will input requirement and area respectively. Grabbing those values, i have to do an ajax call and fetch the necessary data from the database and return it. The ajax call has to be made as and when the input exceeds 4 characters in any of the text fields. As long as there was only one text field i didn't have any problem.
<input type="text" value="requirement" onkeyup="function1(this.value)" />
<input type="text" value="area" onkeyup="function2(this.value)" />
<script>
function function1(valuetosearch)
{
//make the ajax call
}
</script>
<script>
function function2(valuetosearch2)
{
//make the ajax call
}
</script>
How can i combine the two scripts and pass the data in ajax as an array? P.S The main reason for scripting is to do a search combining the two input fields. For example if someone enters house, vehicle in requirement field and place1,place2 in area field. The result search should display the result for the following1) place1 house2) place1 vehicle3) place2 house4) place2 vehicle
you can set id for each elemnt and get the other's value using
document.getElementById("id1").value
and then make the ajax request
http://jsfiddle.net/JMpgU/
$("input").keyup( function () {
var str = $(this).val() + " " + $(this).siblings().val();
alert(str);
//make the ajax call
});
with any number of inputs:
http://jsfiddle.net/JMpgU/2/
$("input").keyup( function () {
var strings = $(this).
siblings().
addBack().
map(function () {
return $(this).
val();
}).
toArray();
//make the ajax call
});
Try this
<input type="text" value="requirement" onkeyup="functionABC()" id="First" />
<input type="text" value="area" onkeyup="functionABC()" id="Second" />
<script>
function functionABC()
{
var searchString=$("#First").val()+" "+$("#Second").val();
//make the ajax call
}
</script>
Pass "searchString" as a param.

Categories