Using function as an attribute for div in jQuery - javascript

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.

Related

Copy value from one text field to another when button clicked

I am trying to get one field to copy over to another field when a div is clicked on, and the code that I have currently is not working. It's showing '0' in field1, even though field2 is set to 1 by default.
$(document).on('click', '#button', function() {
$('#textfield1').val === "document.getElementById('#textfield2').value";
Try with:
$(document).on('click', '#button', function() {
$('#textfield1').val($('#textfield2').val())
});
You're using an odd mix of JS and jQuery here.
Your main issue is that val() is a method, not a property. Therefore your code should look something like this:
$(document).on('click', '#button', function() {
$('#textfield1').val($('#textfield2').val());
});
I'd strongly suggest you familiarise yourself with the jQuery documentation, specifically val() in this case.
It's showing '0' in field1, even though field2 is set to 1 by default.
You were assigning a string to $('#textfield1').val method which is why your code was not having any effect on textfield1's value.
Make it
$(document).on('click', '#button', function() {
$('#textfield1').val( $('#textfield2').val()); //use jquery val method
}
Generally speaking, JQuery offers only functions, and not properties (as #Craicerjack stated), hence remove that === and pass the new value as an argument, as follows:
$('#textfield1').val("yourText");
Also, you're passing a CSS selector rather than just an element ID to the Document.prototype.getElementById() function. Remove that # qualifier!
Moreover, you shoudln't be using a stringified JavaScript expression as a value, otherwise you'll get that exact JS expression as the input value. Rather, don't put those quotes around the expression, so that the interpreter will be evaluating it. Below is some working code.
$('#textfield1').val(document.getElementById('textfield2').value);
However, as #Rory McCrossan pointed out, you're using an odd mix of plain DOM and JQuery, and that makes no sense. It would be more consistent to also read the value of the other text field using JQuery, as follows:
$('#textfield1').val($('#textfield2').val());
Alternatively, you may do not need JQuery and opt for the standard DOM interfaces like in the example below:
document.getElementById('textfield1').value = document.getElementById('textfield2').value;

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...

When I'm trying to append data-id; I got an error

Check this out:
here's a simple code that works fine
html
<select></select>
<button id="btn1">click me</button>
js
$('#btn1').on('click',function(){
var select = $('select');
select.append($('<option>').val('v2').text('text2'));
});
When I'm trying to append data-id I got an error. Any help?
select.append($('<option>').val('v2').text('text2').data-id('id1'));
http://jsfiddle.net/omarmakled/QQ44U/
You can do this 2 ways
select.append($('<option>').val('v2').text('text2').attr('data-id','id1'));
or
select.append($('<option>').val('v2').text('text2').data('id', 'id1'));
http://api.jquery.com/data/
http://api.jquery.com/attr/
First, data-id string is illegal identifier in JS (as it contains hyphen), therefore even if it were available as a jQuery object method, you should have called it like that...
someObj['data-id'](someId);
Apparently, that's too messy for such a simple operation. In fact, there's no such method defined in jQuery.prototype - which instead expects you to employ either attr() (to set any attribute explicitly), or data() (dataset API specific one).
As a sidenote, you don't have to make that many calls: this...
select.append($('<option>', {
value: 'v2',
text: 'text2',
'data-id': 'id1'
}));
... is both more readable AND efficient. Note the quotation marks around 'data-id': object properties can be non-quoted only if they are proper JS identifiers.
JSFiddle.
The correct method to use is data():
select.append($('<option>').val('v2').text('text2').data('id','id1'));
Or if you want an actual attribute you can use attr():
select.append($('<option>').val('v2').text('text2').attr('data-id','id1'));

How can I parse jQuery variable that has the value of attr("title") back to HTML

I have got a variable called name here
Name = $(this).attr("title");
I need to parse this back to HTML, i.e.
Nudging <script>document.write (Name);</script>
But its not working, I think its something to do with scopes
Instead of:
Nudging <script>document.write (Name);</script>
Use something like:
Nudging <span id="someId"></span>
And this line of jQuery:
$("#someId").html(Name);
Check what exactly this is supposed to select in your expression. In the code at the URL you give, you could select like this:
Name = $(".alertdim").attr("title");
See the jQuery selectors reference here: http://api.jquery.com/category/selectors/

Weird Behaviour in jQuery's html method

Any good reason why $("p").html(0) makes all paragraphs empty as opposed to contain the character '0'?
Instead of assuming I found a bug in jQuery, it's probably a misunderstanding on my part.
jQuery only accepts a string as an argument for the val parameter of the html() method. If you pass a number like you are it will call the html() method override that sets the contents of the element but the value of the argument will end up being null or an empty string.
Try this:
$("p").html((0).toString())
Relevant documentation
I guess that at some point, it checks if (newContent == false), and doesn't continue with adding any content? I tried looking at the source, but got a bit lost...
I also guess that this would not be counted as a bug, since the function calls for a string, and if "0" is passed (as a string), it works as expected.
A workaround would be to do this:
var myNum = 0;
$('p').html('' + myNum);
The code performing the html call was within someone else's plugin and rather than modify it, making upgrading it tedious, I just wrote the following tiny plugin that modifies the html method to do as spoon16 recommended.
(function($) {
var oldHtml = $.fn.html;
$.fn.html = function (content) {
oldHtml.apply(this, [content.toString()]);
}
})(jQuery);
It's a little bit of a hack, but it's working for me and doesn't require me to modify the Plugin I'm using.
I just thought someone else might like to see this.
Try using text() instead html().
I geuss you missed part of how jQuery works,
$('p')
returns all paragraphs and the html( val ) function:
Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
http://docs.jquery.com/Attributes/html#val
So if you just want to set the contents for the first p use
$("P").eq(0).html( 'something' );
or to get the html:
$("P").eq(0).html();
http://docs.jquery.com/Core/eq#position
more on jQuery selectors here:
http://docs.jquery.com/Selectors

Categories

Resources