javascript this.value doesn't work? - javascript

sorry for asking that stupid:D However what did i do wrong here?
html:
<div onclick="prompt()" value="test">test</div>
javascript:
function prompt() {
var error = this.value;
alert("sdsd");
}
Thanks!

First off, <div>s don't have a value attribute, so .value won't work. Second, you should not use inline JavaScript.
What you should do is:
<div id="test" value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
// You need to get the attribute from the element
var error = $(this).attr('value');
});
});
If you must use inline events, then you need to pass the element to the prompt() function. The problem is that it doesn't know what this is. This is why you should bind the event as shown above. Anyway, you can also do:
<div onclick="prompt(this)" value="test">test</div>
Then:
function prompt(ele){
// You can't use `.value` because `<div>`s
// don't have a value property
var error = ele.getAttribute('value');
}
P.S. May I also suggest using data-* attributes for this instead of invalid attributes?
<div id="test" data-value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
var error = $(this).data('value');
});
});

The value of this depends on how the function that it appears in was called.
When the browser calls the onclick function from the event trigger, this is the input.
When you call prompt(), because you provided no context and you are no in strict mode, this is the window.
You need to explicitly pass the value.
onclick="prompt.call(this)"
Better yet, don't use intrinsic event attributes in the first place. They mix your HTML and logic and have a whole collection of gotchas to go with them.
Then you have a second problem.
Div elements don't have values. Only inputs and other form controls do. You would need to use .getAttribute("value") instead of .value … but that still leaves your HTML invalid (as well as inappropriate - div elements aren't designed to be interacted with, they give no visual indication that they should be clicked on, and they won't receive the focus should the user not be using a mouse or other pointing device anyway).
You should use a control designed to be interacted with.
Finally, prompt is a built in function, so you should avoid overwriting it and pick a different name instead.
function show_value(event) {
var value = this.value;
document.body.appendChild(document.createTextNode(value));
}
document.querySelector("button").addEventListener("click", show_value);
<button type="button" value="test">test</div>

Div does not have value attribute.
If you need to get the value inside div element you can do it by innerHTML property.
function prompt() {
var error = this.innerHTML; // OR this.getAttribute("value");
}

Related

Determining Element Type from Id

I have a javascript method -testElement() which is called on onclick event -
<script type = "text/javascript">
function testElementType(element){
var elemId = $(element).attr("id");
//Can I determine the 'element' from the 'elemId' ?
// if element is div - do something
// if element is button - do another thing
}
</sccript>
Now consider the following code -
<div onclick="testElementType(this);" id="testDiv" > Test Div </div>
...
<button onclick="testElementType(this);" id="testBtn" > Test Button </button>
So when either of 'testDiv' or 'testBtn' is clicked then the 'testElementType() method is called. In this method I can get the element Id by jquery - $(element).attr("id"); and store it in 'elemId'
Is there any way to find the the type (ie - whether it is a div or button ) of element from 'elemId'?
I know in practice most of the situation we don't have to bother about the element type. Because we can call to different function for two type of element click if we want to do two different type of task.
You dont need to use the id value here. You pass the object into the function iself so all you need to do is this:
function testElementType(element){
var tag = element.tagName;
if(tag=='DIV') // its a div
if(tag=='BUTTON') // its a button
}
using jquery $("#elementId").is("button") will return if elementId is button.
for more answer here
Taken from docs, the tagName selector will return the elements type, you can use it like this.
function testElem(e) {
var t = e.tagName;
// Print the tag name
console.log(t);
}
Something like...
function testElementType(element){
var id = $(element).attr('id'),
tag = $(element).prop("tagName");
});
See this demo fiddle
Try this way to get element type by id
$("#elementId").get(0).tagName

onClick populated by variable without triggering it

I want to append this to my document:
$('#myDiv).append("<div id='myDiv2' onclick="+extElementConfig.onClickDo+">Do</div>");
The snippet above has it's onClick populated by a certain object with properties,
this:
var extElementConfig={onClickDo:sampleFunc()};
Unfortunately declaring a function into the object property also fires it, as was expected.
How can I achieve the above functionality without triggering the
sampleFunc()?
I just need to dynamically populate the onClick event through an object property.
Assuming you have control over the extElementConfig object, remove the parenthesis from sampleFunc
var extElementConfig={extElementPosition :10,extElementId:'mailOrderBtn',onClickDo:sampleFunc};
As Rob. M. pointed out the real problem with your code was the fact you were running the code when it was in the object instead of assigning a reference. And when you tried to assigning the onclick, that had issues too since you are trying to use a function reference when it was a string.
To get your code to run, it would be something like
function sampleFunc () {
alert("clicked");
}
var extElementConfig={onClickDo:"sampleFunc()"};
$('#myDiv').append("<div id='myDiv2' onclick='"+extElementConfig.onClickDo+"()'>Do</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myDiv"></div>
To get rid of this, do not use the sting method to build up the element, instead leverage the power of jQuery. Below is an example where I build a div and pass in some arguments to change the element's text and css when clicked.
function sampleFunc(txt, css) {
$(this).text(txt).css(css);
}
var extElementConfig = {
onClickDo: sampleFunc,
onClickArgs : ["Clicked", {"background-color":"green"}]
};
$('<div/>', {
id: 'myDiv2',
text: 'Do!'
}
).on("click",
function() {
extElementConfig.onClickDo.apply(this, extElementConfig.onClickArgs);
}
).appendTo("#myDiv");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="myDiv"></div>

How to add text to a DIV from array of DIVs

Var divs = $(".txt"); this will return a list of divs with a class txt .
I want to add text to a selected div for example :
divs[4].html("Hello World"); this with return error saying divs[4].html is not a function. why ?
When you access a jQuery object by its DOM array index, you get the HTML element, not a jQuery object, which doesn't have the html() function. Use the eq(n) selector instead:
$(".txt:eq(4)").html("Hello World");
The divs[0] is giving you a DOM reference, not a jQuery object. So, pass that to the jQuery function ($() is shorthand for jQuery()):
$(document).ready(function(){
var divs = $('.txt');
$(divs[4]).html('this one');
});
http://jsfiddle.net/userdude/unu8g/
Note as well the use of $(document).ready(), which will wait until the DOM is accessible. $(window).load() will suffice for this as well, although it may fire after onDOMReady.
The non jQuery way:
document.getElementsByClassName("txt")[4].innerHTML = "banananana!";
Just a side note: I'd suggest learning basic browser javascript before moving to libraries.
It will give you an understanding of how such libraries work and will keep you from being 'locked in' to a specific few

jQuery .click() event for multiple div's

I have some search results that I'm outputting that are of this form:
<div id="result" title="nCgQDjiotG0"><img src="http://i.ytimg.com/vi/nCgQDjiotG0/default.jpg"></div>
There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?
Here's how I'm getting the HTML from above:
$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;
var search_results="<div id='result' title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append($(search_results));
I tried
$('div').click(function(){
alert(this.id);
});
and the alert says "searchresults" (no quotes).
Additionally, this is the perfect opportunity to make use of event delegation. With this technique, you do not have to worry about re-binding click handlers after programmatic insertion of new DOM elements. You just have one handler (delegated) to a container element.
$("#searchresults").delegate("div", "click", function() {
console.log(this.id);
});
See .delegate
You can't have the same ID on multiple tags. You will have to fix that. You can use the same class, but there can only be one object in the page with a given ID value.
this.id will fetch the id value of the item clicked on and this should work fine once you get rid of conflicting IDs:
$('div').click(function(){
alert(this.id);
});
This code should be something this:
var search_results="<div id='result'" + video_id + " title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append(search_results);
to coin a unique id value for each incarnation and append will just take the string - you don't need to turn it into a jQuery object.
you could get the title using $(this).attr("title").val()

Appending a string variable in jQuery

I'm not sure if I have the syntax correct in the code below, I'm trying to append a var to a string parameter within the find function. I'm trying to search for a unique id within each input element of a particular form.
//Get value attribute from submit button
var name = $('#myForm').find('input#submitThis').val();
//Other code that manipulates the name variable
//Submit button in hidden form
$('.submitLink').click(function(){
$('#myForm').find('input#'+name).click();
return false;
});
The element with a submitLink class is supposed to be tied to the submit button in the form. I don't think I have the syntax correct though, when I go back and click the element that has the submitLink class, nothing happens.
The syntax appears fine to me. To be sure the selector is what you are expecting it to be, you could do something like this:
$('.submitLink').click(function() {
var selector = 'input#' + name;
alert(selector);
/* rest of the code */
});
Try adding an alert to test the var inside the event handler (and to see that the handler is fired). Also, if you are looking for an element with a specific id you don't need to include the element type. Like this:
$('.submitLink').click(function (event) {
event.preventDefault();
alert(name);
$('#' + name, $('#myForm')).click();
});
NOTE: If you are trying to find an element by its name rather than ID you must use $("input[name='foo']").

Categories

Resources