how to reformat jQuery / JS function properly? - javascript

can't figure out how to write this as a function without the jQuery
This works & returns what I need:
var state = $('#order_ship_address_attributes_state_id option:selected').text()
Which is the text from an options list aka "Florda" instead of "3534"
<option value="3534">Florida</option>
However, I would like it written in this convention instead:
var city = ((document.getElementById('order_ship_address_attributes_city')||{}).value)||"";
... to match the rest of my variable declarations.
Trying this but error read "Uncaught TypeError: Cannot read property 'text' of null"
var state = ((document.getElementById('order_ship_address_attributes_state_id option:selected')).text())
Can't figure out the correct way to write this — any help would be much appreciated : )

As #benvc pointed out. You want to use .textContent instead of calling the .text() jquery method.

Related

taking play framework object in a javascript variable

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();

Using function as an attribute for div in jQuery

Since my selector options and logo images have the same names i want to use this to make a function that changes the image when you select. I've tried this:
$(function(){
$(selector).click(
$(function(){
$(div).attr("src", "($(selector).val()).png")
}))})
Buuut, no sauce :(
With help from parth718 got to this:
$(function)(){
$(selector).click($(div).attr("src", "images/logos/"+($(selector).val()+".png")))};
But now i'm getting error: TypeError: g.handler.apply is not a function.
I'm running jQuery 1.12.2 from Google's CDN on this.
Toughts? .-.
In PHP, "$file.png" gives you the result you want, not in javascript ...
You have to concatenate strings with your var with the plus operator.
As said, you have to do a :
$(logodiv).attr("src", $(selector).val()+".png")
instead of
$(logodiv).attr("src", "($(selector).val()).png");
try this
$(logodiv).attr("src",($(selector).val()+".png");
You are using variable inside "" therefore the attr will be changed as
src="$(selector).val().png"
exact string will be there and not the selector variable.

How to set attributeName to "value"

I'm trying to assign "value" as attributeName to a jQuery object. However, I am getting the "Object doesn't support this property or method" error. Here is the line:
$(rowElem).attr("value","");
I think I am getting this error because jQuery treats the word "value" as another method and not as an attribute. I will gladly appreciate help from you guys. Thanks in advance! :)
Hi you are doing it wrong , Jquery need a selector whether its id , class or tagname
for Id you need to add prefix "#" For Class you need to add prefix "."
and tag name as it is....
So your fixed code is something like that
$("#rowElem").attr("value","My New VAlue");
When ever you use value I think the only jquery you will use is
$(rowElem).val("");
It is however, not a good practice to use 'value' as any other attribute, what you can do is with HTML5, make your own attribute as
<tr data-value="somevalue" />
and use the attribute like
$(rowElem).attr("data-value", "");
and you can use that attribute's value like
var val = $(rowElem).attr("data-value");
There is nothing wrong with the code that we can see. It looks like you don't have jQuery loaded in the DOM. See my tests below.
i.e. If you go to backbonejs.org and type in the following in the console:
if(jQuery)
console.log('jQuery has loaded');
// logs 'jQuery has loaded'
var rowElem = 'div';
$(rowElem).attr('value', '');
It successfully adds 'value' to the divs.
However, if you use a site without jQuery like underscorejs.org, it won't work:
if(jQuery)
console.log('jQuery has loaded');
// ReferenceError: jQuery is not defined
var rowElem = 'div';
$(rowElem).attr('value', '');
// TypeError: Object #<HTMLDivElement> has no method 'attr'
You need to get it access to jQuery and your problem should be solved.
There is no such attribute in jquery or javascript. Both treats value as a separate function.
You can try using:
jquery: $(rowElem).val("urVal");
javascript: rowElement.value = "urVal";
use this.. provide value in val
$(rowElem).val("value");
hope it works...

Dynamic onchange with Jquery

I am attempting to use jQuery to dynamically populate the onChange attribute in a text field to run multiple functions. However i get an error in the console stating
TypeError: required is not a function
When i type into the console required('test'); the function exists and returns true.
HTML
<input id="test">
jQuery
var list_of_functions = get_validation(); //this returns a string "required('test'); valid('test');"
$('#test').attr('onChange', list_of_functions);
Then when i go and change the fieldtext, I get an error that the function doesnt exist. Any help? Thanks.
Thanks to all the super helpful comments. I have found a better alternative to what I was attempting to do.
How to turn a String into a javascript function call?

document.getElementById works, but $ is throwing an error

I have this code here :
<select id="test">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
In my script I have these two line of code, one is JavaScript and another one is jquery like so :
var e = document.getElementById("user");
var e1 = $("#user");
I even printed out those in my console like this :
console.log(e)
console.log(e1)
They are printing same thing. But when I write a on change event code like this :
$("#user").change(function() {
console.log(e.options[e.selectedIndex].text)
});
It is exactly printing what I choose from drop down. That this javascript way of fetching from dom is working. The same thing with e1 like so :
$("#user").change(function() {
console.log(e1.options[e1.selectedIndex].text)
});
is throwing an error :
Uncaught TypeError: Cannot read property 'undefined' of undefined
(anonymous function)create:167
f.event.dispatchjquery-1.7.1.min.js:3
f.event.add.i.h.handle.i
(seen from chrome's developer tools)
Whats going on? I'm new to both Javascript and jquery! Why in my case jquery is not working?
Since you're using jquery and e1 is a jquery object try:
console.log(e1.find('option:selected').text())
To grab the actual element you can use get():
var select = $('#select').get(0) // Grab original DOM element
select.options // It'll work now...
var e = document.getElementById("user");
this creates an javascript object.
var e1 = $("#user");
This creates an jquery object. You can't use javascript properties on this. You must use jquery properties.
The select menu you give at the top of your article has an id of 'test' not 'user'. I assume the code you're actually working with has an id of 'user'. e1 is a jQuery object, so to access it's value use e1.val() instead of e1.options[e1.selectedIndex].text. You're mixing javascript code with jQuery code.
e1 is a jQuery object because you used jQuery to select it. It is not the normal js dom element, which is how you are trying to use it.
This should work better:
$("#user").change(function() {
    console.log(e1.val());
 });
val() is a jQuery function that provides a unified wrapper around form element values so you don't need to find the selected index, access that from the select obj, etc. This is one of the things jQuery does that makes life easier.
console.log(e1[0].options[e1[0].selectedIndex].text)

Categories

Resources