While trying to find a solution to this problem I came across this post which suggests using the appendTo method like so:
$('<input[type="text"]').appendTo('div').addClass('foo');
There are times where I'm using append more than the former. Is there a way I can chain methods to a newly inserted element using append?
HTML
<div id="foo">
<input type="text" />
</div>
JS
Add new element
$('body').on('click', 'a', function(e) {
e.preventDefault();
$('div').append('<input type="text" />').addClass('bar');
});
If you still want to use append you can pass jQuery object to it instead of HTML:
$('div').append($('<input type="text" />').addClass('bar'));
$('div').append($('<input type="text" />').addClass('bar'));
.bar {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
Related
Some introduction:
I'm creating a form in Django.
In my template I'm trying to select the final element of that form and attach a <hr> html element to help clean up the visual clutter.
I've tried selecting the Forms ID and inserting adjacenthtml as well as appending raw html. I have also tried passing raw html into bootstrap in my form but this has also failed to render.
tldr; I am trying to append a <hr> element to something I am targeting in Jquery
function addHoriztonalRule() {
document.getElementById("form").insertAdjacentHTML(
"<hr>");
}
You failed to add the position of where you wish to place the HTML in relation to the element.
MDN: A DOMString representing the position relative to the element; must be one of the following strings:
'beforebegin': Before the element itself.
'afterbegin': Just inside the element, before its first child.
'beforeend': Just inside the element, after its last child.
'afterend': After the element itself.
function addHoriztonalRule() {
document.getElementById("form").insertAdjacentHTML('afterend', '<hr>');
}
addHoriztonalRule()
<form id="form" method="post">
<input type="button" value="button">
</form>
With jquery you can use this:
function addHoriztonalRule() {
$('#form').after("<hr>");
}
addHoriztonalRule();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="text" value="hi" >
</form>
However, it is better to share the structure of the page to learn more from DOM and how to call the function to better guide
I'm trying to react on <input> events with jquery, to modify a background label in as soon as the input contains text:
$('#inpt').on('input', ':text', function() {
Window.alert("test");
$('#mytext').attr('background', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input id="inpt" type="text" placeholder="Type in here" />
</div>
<span id="mytext" style="background:green">Test</span>
Result: nothing happens. I don't even get the alert. Why?
The problem here that you use selector inside you on function cause the $('#inpt') is the container for looking the selector. But in this case the container is the selector (:input) you define in on() function too then it doesn't work and the Window wrong typo too.
attr is use to update the attribute of the element and background is not included inside attr list. Then you should wrap the background: red inside style attr or using css({background:red})
$('#inpt').on('input', function() {
window.alert("test");
$('#mytext').attr('style', 'background:red');
});
You should use with document and keyup
$(document).on('keyup', '#inpt', function() {
alert("test");
$('#mytext').css({'background': 'red'});
});
I have simple from which consists by inputs like that:
<form id='some-form'>
....
<input type="radio" data-type="4" data-value="25" data-id="68" name="req-68">
....
</form>
I'm trying to loop through this form and get data values:
$('#some-form').filter(':input').each(function (i, element) {
console.log(element.value);
console.log(element.attr('data-value'));
}
element.value holds value 'on' or 'off' depending radio is chosen or not and it works properly but when I try to call element.attr('data-value') it throws an error.
So how can I extract data-value in this loop?
use .children() instead of .filter().
The former will get you the elements inside the form, the latter will filter all elements $('#some-form') will provide.
HIH
EDIT
as pointed out by gaetanoM and connexo, there is also the issue of using element.attr() without the $() which you will need since .attr() is a method of jQuery, not JS
$('#some-form').children(':input').each(function (i, element) {
console.log(element.value);
console.log($(element).attr('data-value'));
//
// or
//
// console.log(element.dataset.value);
})
console.log('end');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='some-form'>
<input type="radio" data-type="4" data-value="25" data-id="68" name="req-68">
</form>
if you use newer jQuery >= 1.4.3
You can use like this.
$(this).data("value");
OR
$(this).data().value;
Inside your .each() function element is a regular HTMLElement, not a jQuery object.
Either wrap that using $(element) (or even $(this)) which allows to use
jQuery's $.attr()
$(element).attr('data-value')
or, even better, use the corresponding native DOM Api method
element.getAttribute('data-value'))
Since you are accessing a data- attribute, the DOM Api has a special object dataset to access these (from IE 11 upwards):
element.dataset.value
In case you have a name for your data-attribute like data-cmon-lets-go you can access it using camelcase notation:
element.dataset.cmonLetsGo
This could also be done with vanilla javascript.
document.querySelectorAll('#some-form input[type="radio"]').forEach(radio => {
console.log(radio.value, radio.dataset.value);
});
<form id='some-form'>
<input type="radio" data-type="4" data-value="25" data-id="68" name="req-68">
</form>
In the each loop you are actually in the context of the radio element so you can use $(this).attr('data-value') and it will work. The following is a working code.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form id='some-form'>
<input type="radio" data-type="4" data-value="25" data-id="68" name="req-68">Hello
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$('#some-form :input').each(function (i, element) {
console.log(i);
console.log("element", element);
console.log($(this).val());
console.log($(this).attr('data-value'));
});
});
</script>
I have a input from website which defines like this:
<input type="text" name="postdb[title]" size="60" value id="title" class="input_text">
I've tried this:
document.getElementsByName('postdb[title]')[0].value='test'
and this:
document.getElementById('title').value='test'
but it doesn't work,how to set the value of this input use javascript?
edit:
I found that this input is insideof <form name="FORM..,so how to find it in that form use javascript?
edit:solved;
its actually inside of FORM from iframe,so I just use this:
var vform =document.frames['main'].document.forms['FORM'];
vform.elements['title'].value='test'; thanks for help,
Your DOM was probably not loaded yet.
<!-- this will fail -->
<script type="text/javascript">var el = document.getElementById('element');</script>
<div id="element"></div>
The above example will fail because we are trying to search an element that has not yet loaded. A mistake easily made!
<!-- this will not -->
<div id="element"></div>
<script type="text/javascript">var el = document.getElementById('element');</script>
By running the javascript after the required DOM has loaded, we are able to find it.
use this
<input type="text" name="postdb[title]" size="60" value="" id="title" class="input_text">
document.getElementById('title').value='test';
Try with this:
$(document).ready(function() {
document.getElementById('title').value = 'test';
});
Demo Here: JS Fiddle
Both should work for you but,make sure when you are calling document.getElementById(); or document.getElementsByName(); does the <input> element exist in your page?
I'm iterating over a div using :
Can I access a hidden parameter in this div within the iteration ?
<DIV>
<div id="myDiv" <input type="hidden" name="Language" value="English"> />
</DIV>
$('#myDiv div.id').each(function() {
//access a hidden parameter of the current div here
});
You can use one of the following methods:
$('#myDiv div.id').each(
function(){
parameter = $(this).attr('data-hidden-parameter');
/* or:
parameter = $(this).data('hidden-parameter');
*/
});
The first parameter = $(this).attr('data-hidden-parameter') requires the following structure:
<div class="id" data-hidden-parameter="value"><!-- other stuff --></div>
Whereas the latter works with getting/setting with the data() method of jQuery:
$(selector).data('hidden-parameter','value'); // sets
$(selector).data('hidden-parameter'); // gets
If you mean retrieving text, or other content/attributes, from a hidden element that's a child of the div.id element, with mark-up such as:
<div class="id">
<input type="hidden" value="somethingOrOther" />
<span style="display: none;">Some text in a hidden element</span>
</div>
You could retrieve that value with:
$('#myDiv div.id').each(
function(){
parameter = $(this).find('input:hidden').val();
/* or:
parameter = $(this).find('span').text();
});
Note your jQuery selector implies you're iterating over a number of elements, based on the class of those elements, while your class-name, id, implies you're trying, instead, to search based on the id of an element. This might be pseudo-code to demonstrate your approach, but please don't use a class-name of id. It's perfectly valid, but it's terribly confusing. Albeit this is simply my own, personal, objection and response.
Edited, to supply a more targeted answer, by amending one of the above suggestions with an appropriate selector:
var parameter = $('#myDiv').find('input:hidden[name="Language"]').val();
References:
attr().
data().
find().
:hidden selector.
text().
val().
your html code is invalid: if you mean
<div id="myDiv"><input type="hidden" name="Language" value="English"></div>
this will target your input
$('#myDiv input[type="hidden"]')
You cannot put a tag inside another tag (or, in HTML or HTML-compatible XHTML, use self-closing tag syntax on a div). Your HTML is invalid and subject to whatever error recovery parsers care to put it though.
If you had, for instance:
<div id="myDiv">
<div class="id">
<input type="hidden" name="Language" value="English">
</div>
</div>
Then you could do:
$('#myDiv div.id').each(function(index, element) {
var foo = $(element).find('input').val()
});
… but you are probably better off using data-* and jQuery's data() method