getElementById inside a div - javascript

I'm using a Javascript to change the text on a form submit button, this is the code I'm using:
<script type="text/javascript">
$(document).ready(function(){
document.getElementById("button").value="New Button Text";
});
</script>
The code work perfectly, but I need to change it so that it effects the id #button within a div with the id of #formwrap. So basically I need to .getElementById("button") contained within the div with a id of #formwrap

If you are already using jquery, why not just do
$('#formwrap #button').val('New Button Text');
?
It's simply CSS-like selector, similar to what you'd use in querySelectorAll().
It will match for example this button:
<div id="formwrap"><input type="button" id="button"></div>
But keep in mind that only one element can have the same ID.
Maybe you wanted class? Then you'd use .button instead of #button.

Related

prev() not returning div element

I'm probably being especially dense about this, but I can't get an element to return using prev(). My basic HTML structure is:
<div>
<table></table>
</div>
<input type="button">
Where when I press the button, I want to get the previous element (the div element). To achieve this my button has a function attached to it with
var nearestDiv = $(this).prev();
When I've checked the contents of nearestDiv in the console it appears to be some kind of JQuery object rather than a HTML div. I've tried popping .val() at the end of .prev() but this comes back empty. How can I get the div element?
Note that my button is generated on the fly and doesn't have anything which identifies it.
you need to use jquery get function, to get a native html object and not the jquery wrapper:
$("input").on("click",function(){
console.log("jquery wrapper:",$(this).prev());
console.log("native html div object:",$(this).prev().get(0));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table></table>
</div>
<input type="button">
If your html structure is same as you provided in the question, it will definitely return the div element. Note that there is no val() method for div element, you need to either use .html() or .text() inorder to get the contents.
$("input[type='button']").click(function () {
var div = $(this).prev();
alert(div.html());
alert(div.text());
});
Fiddle
You need to give .text() or .html() for standard HTML Elements. So your code should be:
var nearestDiv = $(this).prev().html();
var nearestDiv = $(this).prev().text();

How to .append() an object

I'm making a simple game in javascript and I would like to .append() a box. To serve as a bullet. But I'm stuck. This is what I have
var existingdiv1 = document.getElementById('bullet');
and
$("#test").click(function() {
$("div").append([existingdiv1]);
});
It wont create additional "divs" when I press the button "#test".
You will have to select the existing div (I guess this is the bullet?). Then append it.
Here's and example:
Working Demo
Javascript:
$("#test").click(function(){
$("#appendToThis").append($('#bullet').html());
});
Html:
<input id="test" type="button" value="click" />
<div id="appendToThis"></div>
<div id="bullet"><div>BANG</div></div>
You will see the word "bang" be appended everytime you click. You can remove it by using the empty() method on the test div.
From the .append documentation:
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).
It seems like you want to clone [docs] the element first:
$("div").append($(existingdiv1).clone());
// or simpler
$("div").append($('#bullet').clone());
Note though that if you have multiple div elements on your page, $("div") will select all of them and the element you pass to .append will cloned automatically (as stated in the documentation).
You should append the element only to a single div.
I believe you wanted to add a new div to the existing div, so your code has been reversed the append order. and you need wrap the existing div by $('#bullet')
Try this
$('#bullet').append('<div></div>');
You can use .clone()
$("#test").click(function(){
$("#appendToThis").append($('#bullet').clone());
});

How to access a hidden Dom Element with jQuery?

I have a HTML Div (I'm using Twitter Bootstrap to hide-show div2) looking like this:
HTML:
<div id="div1">
<button id="mybtn">Button</button>
<div id="div2" class="modal hide fade span12" style="display: none;">
<button id="anotherButton" data-char="">AnotherButton</button>
</div>
</div>
With jQuery im trying to change the Value of data-char while im clicking on mybtn. But without success cause div2 is hidden. console.log($('#anotherButton')); return an empty array.
Is there a way to access hidden DOM with jQuery or Javascript?
*Edit: *
By trying this dont work better , return undefined:
$('#mybtn').live('click', function(e)
{
//or e.preventDefault();
$('#anotherbutton').attr("data-char", "assigned");
alert($('#anotherbutton').attr("data-char"));
});
You can assign it
Live demo
$(function(){
$('#anotherButton').attr('char', "assigned");
alert($('#anotherButton').attr('char'));
});​
on Button click
Live Demo
$(function(){
$('#anotherButton').attr('data-char', "assigned");
alert($('#anotherButton').attr('data-char'));
});​
It looks like data method will not work on elements which are in hidden state. You should use attr method.
This should work fine
$(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$("#anotherButton").attr("data-char","new value");
});
});
Working sample http://jsfiddle.net/kshyju/a7Cua/4/
The fact that it is hidden changes nothing. The problem is probably that the js code is before the button HTML. Either put it after, or put it in a listener like $(document).ready() to make sure it has been processed when your try to access it.
Try $(button:hidden)
This usually works for things like this,
Source:http://api.jquery.com/hidden-selector/

Remove attribute of HTML tag

Is it possible to remove the attribute of the first HTML <div> tag? So, this:
<div style="display: none; ">aaa</div>
becomes
<div>aaa</div>
from the following:
<div style="display: none; ">aaa</div>
(bbb)
<span style="display: none; ">ccc</span>​
Or pure JavaScript:
document.getElementById('id?').removeAttribute('attribute?')
To remvove it from literally the first element use .removeAttr():
$(":first").removeAttr("style");
or in this case .show() will show the element by removing the display property:
$(":first").show();
Though you probably want to narrow it down to inside something else, for example:
$("#container :first").removeAttr("style");
If you want to show the first hidden one, use :hidden as your selector:
$(":hidden:first").show();
Yes, in fact jQuery has something for this purpose: http://api.jquery.com/removeAttr/
You can use the removeAttr method like this:
$('div[style]').removeAttr('style');
Since you have not specified any id or class for the div, the above code finds a div having inline style in it and then it removes that style from it.
If you know there is some parent element of the div with an id, you can use this code instead:
$('#parent_id div[style]').removeAttr('style');
Where parent_id is supposed to be the id of parent element containing the div under question.
You say "remove the attribute" — do you mean to remove all attributes? Or remove the style attribute specifically?
Let's start with the latter:
$('div').removeAttr('style');
The removeAttr function simply removes the attribute entirely.
it is easy in jQuery just use
$("div:first").removeAttr("style");
in javascript
use var divs = document.getElementsByTagName("div");
divs[0].removeAttribute("style");

jquery toggling a div - how to do this with multiple ids?

I am new to Jquery. My setup is as follows:
I have a series of divs that need to be able to be toggled (display hidden and shown). Each div has an action that can be performed so a unique ID will be necessary to know from which div the event came from.
To toggle the div I have a button for each div (which is not located within the div to be toggled).
Right now without jquery, I use the button's onclick event to pass the ID of the corresponding div to be toggled. Using the unique ID I can do the following:
function toggleFlag(divId) {
var div = document.getElementById(divId);
div.style.display = (div.style.display=="block" ? "none" : "block");
}
divId is unique so I also know where the event comes from if action within the div is performed.
the anchor code looks something like this:
onclick="toggleFlag('id-111');"
where the '111' is the unique id
First off, is it even worth it to use jquery for this if the extent of my javascsript isn't much more complicated (aside from maybe simple ajax).
More importantly, how would this properly be done using jquery?
Update: I am very close to solving this. I managed to get it to work using one of the suggestions below requiring unique class names for each button. A couple of the methods suggest implementations where the class name is the same for all buttons (I want this in order to be able to statically assign styles to the button class), but I could not get these to work. Could somebody please elaborate on the solution? Thanks!
Let's say that you build your anchors to have an id that corresponds with the id of the DIV to toggle and further that they all have a common CSS class. For example,
Toggle
<div id="d_111">Some stuff.</div>
Now you could use jQuery to build the click handlers for all of these pretty easily.
$(function() {
$('a.toggleButton').click( function() {
var divId = $(this).attr('id').replace(/a_/,'d_');
$(divId).toggle();
});
});
You could do something like this:
HTML:
<button id="btnId1" class="divId1" value="Click me to toggle divId1"/>
<button id="btnId2" class="divId2" value="Click me to toggle divId2"/>
etc...
<div id="divId1">div 1</div>
<div id="divId2">div 2</div>
etc...
SCRIPT:
$(function() {
$("button").click(function() {
var divId = $(this).attr("class");
$("#" + divId).toggle();
});
});
This approach has the advantage of only defining the event once for all buttons. You could also use another strategy for storing the div id in the button information, like a non-standard attribute - which jquery can pick up as well, or make the div id a part of the button id like so:
<button id="btn_divId1" value="Click me to toggle divId1"/>
<div id="divId1">div 1</div>
and then extract the id of the div from the id of the button clicked (personally this is the approach I'd take)
Hope this helps
EDIT: To answer the first question, yes you would benefit from doing this with jQuery since it would shorten the amount of code that you are writing and it would allow you to move to unobtrusively assigning events to the buttons which is a good thing :)
EDIT 2: Using non-standard attributes:
HTML:
<button id="btnId1" divid="divId1" class="btnToggle" value="Click me to toggle divId1"/>
<button id="btnId2" divid="divId2" class="btnToggle" value="Click me to toggle divId2"/>
etc...
<div id="divId1">div 1</div>
<div id="divId2">div 2</div>
etc...
SCRIPT:
$(function() {
$("button").click(function() {
var divId = $(this).attr("divid");
$("#" + divId).toggle();
});
});

Categories

Resources