I have a select option tags in my HTML which are populated via api calls
<select name="channel" id="selectName" onChange="getSelectedName(this)">
<option value="">Select Name</option>
</select>
In my JS, I'm getting the values of each option with the following lines of codes
// get selected name
function getSelectedName(selectoption){
let name = selectoption.value;
console.log(name);
}
This log the exact value of the channel in the console which is great.
My Challenge:
I have other functions in my project that need the exact values of the value being generated by that function.
How do I access that exact value globally so as to ingest them into other functions.
What I have done:
I've tried making the name global, however I have not had any headway with it.
Thanks in anticipation of your response.
If they are on the same page, you should be able to use
getElementById("selectName").value
This gets the actual selected value of your <select>
You can access the select element value using getElementById. If you want to run other functions when select event happens use this kind of solution
function getSelectedName(selectoption){
let name = selectoption.value;
function1(name);
function2(name);
}
Or you can use event handler
document.getElementById("selectName").addEventListener("change", function1);
document.getElementById("selectName").addEventListener("change", function2);
Related
I'm trying to write an app in Javascript, HTML and CSS, in which I take information from the user via input fields and save it to variables that are to be used later. I've assigned empty global variables at the beginning of the script, which are then supposed to be reassigned when event listener functions run. By logging to the console from inside and outside of the functions, I can see that the user input is being assigned to the variable within the function, but not outside of it.
Example code:
let inputName;
const person = document.getElementById('person');
function getName() {
inputName = person.value;
//if console.log(inputName) is here, the assigned value for inputName will be logged to the console
};
person.addEventListener('change', getName);
//if console.log(inputName) is anywhere outside of getName(), the value will not appear on the console
Plus the corresponding HTML:
<div>
<label for='person'>What is your name?</label>
<br>
<input type='text' id='person' placeholder='John Doe' required>
</div>
I've tried all sorts of variations of this, but still haven't found the solution; any ideas as to how to fix/rewrite this?
Okay, I figured it out. Tempted to just delete the thread out of embarrassment, but will keep it up as I imagine I'm not the only newbie that gets blindsided by this sort of thing...
In a nutshell, having come to event listeners fairly recently, I neglected to take into account that the script will run substantially faster than I can enter a name into the input field, and thus will run the console.log() much earlier than I can hope to run the event listener function to assign a value, regardless of where I type console.log()... Facepalm! Anyway, it looks like #JakeAve called it - and I'll definitely remember to use setTimeOut() to get round this sort of thing in the future, that's a neat strategy.
Thanks everyone for taking your time to help out - much appreciated!
I have a map declared in template parameters with the following syntax
#(formData : scala.collection.Map[String, scala.List[String]], previousData : scala.collection.Map[String,String], resultList: scala.List[String])(implicit flash: play.api.mvc.Flash)
I want to read the previousData map object and want to store it in a javascript variable.
I actually want to set the value in a textbox by fetching the value from the map object. I know that I can use document.getElementById in javascript to set the value of a particular textbox. Could anyone please help? If some other way is possible please let me know.
I tried the following method but it isn't working.
function loadPreviousData()
{
if(#previousData != null)
{
var x = #{previousData.getOrElse("name",null)};
alert("Name is " +x);
}
}
Yes you can use JQuery which is widely used nowadays. Let's say txtname is the id of your textbox then you can do like this
$("#txtname").val(x);
Here x is the variable in which you extracts the data.
I haven't found a way to directly solve this, but there's a method which worked for me and so I'm sharing.
I used a Json object instead of a Map to tackle this. The required data in the key value format was filled in JSON object and passed that JSON object in the form of a String using toString() method.
Ok(views.html.serviceReplay.render(formData, resultList.toList, fetchFormDataInJson.toString,newFlash))
In the view section, this Json object was obtained as a string.
#(formData : scala.collection.Map[String, scala.List[String]], resultList: scala.List[String], previousPageData : String)(implicit flash: play.api.mvc.Flash)
And finally, in order to obtain in a variable at the view section, following instruction was used.
var previousDataInJson = JSON.parse('#previousPageData'.replace(/"/g, '"'));
This worked for me. Hope it helps others.
Additionally, if we want to do via Map object I found a solution to that as well.
I was unable to directly use #formData directly in the javascript code, but it worked in the HTML section, therefore I used in the following scenario.
<select name="service" id="service">
<option value="">Select Service</option>
#for(serviceName <- formData.getOrElse("service",null)) {
<option value="#serviceName">#serviceName</option>
}
</select>
Now the value has been assigned to the serviceName, therefore, this can be easily retrieved using JQuery using the following syntax.
var service = $("#service").val();
I want to access form input value in services.
var emailId = document.getElementById("save_quote_email").value;
console.log("emailId="+emailId);
console.log("emailId2="+angular.element('#save_quote_email').val());
I am able to get value using document.getElementById("save_quote_email").value but not using angular function angular.element('#save_quote_email').val()
It gives error
Error: [jqLite:nosel] Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element
http://errors.angularjs.org/1.2.16/jqLite/nosel
Please view this plunker http://plnkr.co/edit/Op1QDwUBECAosPUC7r3N?p=preview for complete code.
in dtoresource.js line numbe2 21.
You can't use angular.element to select by id or some other selector Link provide by you give full info as below
"Note: Keep in mind that this function will not find elements by tag name / CSS selector. For lookups by tag name, try instead angular.element(document).find(...) or $document.find(), or use the standard DOM APIs, e.g. document.querySelectorAll()"
you may use document.query selector as follow
var queryResult = document.querySelector('#save_quote_email');
var emailId2 = angular.element(queryResult);
Here is working plunker http://plnkr.co/edit/mC0JKTZpdnvqyBpihLRW?p=preview
Also this https://stackoverflow.com/a/23626251/5621827 will help you to understand it batter
Instead of trying to answer your question I am going to rather direct you to the correct way of using Angular.
You should never try and select input values, that is what ng-model is for.
ng-model bind the input to a value. As soon as the value changes Angular automatically updates the scope value, no functions of getting data necessary.
I can't make heads or tails out of your plunkr code but you should not do this:
var queryResult = document.querySelector('#save_quote_email');
Also you are trying to access the DOM from a factory, you should rather pass the needed value to an exposed function of the factory and call the function in your controller.
In your controller autoQuoteCtrl you should use a simply scope value for your input like so:
$scope.email = "";
And in your index the input should read:
<input type='text' ng-model="email" />
{{ email }}
Do not use convoluted variables like AutoQuote.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails[0].EmailAddress in your scopes, you should assign the values when they are received from the resource.
$http({url: url}).then(function (rs) {
$scope.email = rs.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails[0].EmailAddress;
}
I have a SELECT html element which has the onchange event like this:
onchange="myFunction(this)"
What kind of object is this in this context?
function myFunction(control){
var jqObject = $(control);
...
..
var jqObject2 = jqObject.find('select.mySecondSelect')
}
Inside my function I get another object with jQuery (jqObject2) which represents another select HTML Element and I want to cascade this object to a similar function like myFunction(this)
So, how can I transform the jQuery object as JavaScript object but like this as a parameter does?
I found in some posts that calling the jqObject.get(0) or jqObject[0] is what I should need, however I don't think it is the same thing. Because with get(0) I am getting the native DOM element but not specifically as an object AFAIK.
Update
This will be the whole scenario:
HTML
<select name="lstCountry" class="country" onchange="onCountryChange(this)">
<option value="USA">USA</option>
<option value="MEXICO">Mexico</option>
</select>
<select name="lstState" class="state" onchange="onStateChange(this)">
....
</select>
JS
function onCountryChange(control){
var oCountry = $(control);
var oState = oCountry.closest('tr').find('select.state'); //<== oState is never empty or unspecified. I always get the object correctly.
//do operations related to the country
//specific case, call the onStateChange
onStateChange(oState.get(0)); //<== Here!!
}
function onStateChange(control){
var oState = $(control); //<== When I call this from the function onCountryChange, control is equals to unspecified. BUT not when the user really perform the onchange on the control state (select Element) manually
//do operations related to the state
}
this in an onXXX attribute is the DOM element itself. So in this case it's the <select> element that the user changed. $(control) creates a jQuery object that contains the DOM element. Given a jQuery object that contains a collection of elements, you can use jqObject.get(n) or jqObject[n] to get the nth element in the collection. So if there's just one element in the jQuery object, jqObject[0] will return that element.
What you found in those post is the correct thing.
The this in your code (onchange="myFunction(this)") refers to the raw html element (that the attribute is applied).
So using jqObject2[0] will point to the raw html element of the followup query.
In JavaScript this always refers to the “owner” of the function we're
executing, or rather, to the object that a function is a method of.
When we define our faithful function doSomething() in a page, its
owner is the page, or rather, the window object (or global object) of
JavaScript. An onclick property, though, is owned by the HTML element
it belongs to.
Via- http://www.quirksmode.org/js/this.html
And as #Barmar mentioned, jqObject.get(0) or jqObject[0] basically returns the first object from an array, jqObject.get(1) or jqObject[1] returns the second and so on.
Hi guys I want to know how can I get the values of this code:
<input type="radio" name="pgto" value="entry1" class="payment" />
jQuery(".payment").click(function(e){
alert(e);
}
when I click in payment radio, the alert msg says [object object],
I try to search how can I get the values of the 'e' variable function,
I found this 'e.currentTarget' current Target, if I do something like e.currentTarget.value it will
alert de value entry1 if I do e.currentTarget.name it will alert 'pgto'.
What I want to know is what are the options for object variable 'e'.
I know that there is the currentTarget option. What are the others???
Like:
alert(e.something);
if you run this with firebug then you can see all the properties of e:
jQuery(".payment").click(function(e){
console.log(e);
});
You are grabbing every single element on the page that has the class payment. This might give you inputs, or divs, etc. You want that exact <input>, place a id on it.
You are attempting to alert the event-object as #Quentin has pointed out, read his comment
If you want to get the value of a input like this, you're going to have to write: $(*get input*).val()
If you wanted to test the printing out of an object, alert() is not the function to use. Try console.log( *object* )