JQuery selector does not work in dynamically created content? - javascript

I am trying to retrieve the .html() .val() or something else within a html element, this is my html code (generated dynamically):
<div class="presupuesto"><h2 class="precio" id="precio" value="1202">1.202,00 €</h2>
I need the .val() attribute!
With JQuery and JavaScript I want to show, what option from a select has been selected and then show the information about h2 tag (price). This is my JS code:
$('select').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
alert(valueSelected);
alert(("#precio").val());
});
The first alert(valueSelected) works well, but the second one triggers a TypeError
Thanks in advance!

As you said that you have dynamically generated elements. Then You need to use event-delegation:-
$(document).on('change','select',function(){
alert($(this).val()); // to get select value
alert($('#precio').attr('value')); // try to use data-attribute which is standered way
});
Note:- Since <h1>,<h2>..,<div>,<ul><li><p>.... these elements don't have value attribute (In standered way). So use data-attribute option for them like below:-
<h2 class="precio" id="precio" data-value="1202">1.202,00 €</h2>
And then change jQuery code just a bit like below:-
alert($('#precio').data('value'));

Related

HTML Select Tag with Javascript

I want to alert the value of a specific option in my dropdown when it is clicked. Here is my code:
$("select").change(function () {
alert($("option").html());
});
I've tried using .text() and .val(), but neither seems to work.
Assuming you're not using a select[multiple] element, "The jQuery Way™" to get the value is:
$('select').change(function () {
console.log($(this).val());
});
which really might as well be:
console.log(this.value);
The problem with your existing code is that $('option') selects all option elements, and then .html() gets the innerHTML of the first option element in the collection.
You don't want the first option on the page, you want the current value of the select element.
alert($(this).val());
This should work i guess, if you want the value and not the text
Simple enough
$("select").change(function () {
alert($(this).val());
});

Jquery: Get attribute value of dynamically created element

I created a div dynamically, and on click event I want to get it's attribute value, but when I try to do that, it throws me an error. "jQuery(...).attr(...).val is not a function", refer my code below
jQuery("#target1").on("click", function(){
jQuery("#target_block").append('`<div id="target2" data-rel-pid="12345">Click Me</div>`');
});
jQuery("#target2").on("click", function(){
var bid=jQuery(this).attr("data-rel-pid").val();
});
Actually the error is in this line :
var bid=jQuery(this).attr("data-rel-pid").val();
There is no need to cal .val() on .attr()
var bid=jQuery(this).attr("data-rel-pid");
.attr() itself will return the value.
For more to this, refer here.
Remove the .val()
jQuery("#target2").on("click", function(){
var bid=jQuery(this).attr("data-rel-pid");
});
As you are already using jQuery and you want to fetch a data attribute you can also do something like this.
$("#target2").on("click", function(){
var bid=$(this).data("rel-pid");
});
As target2 is being appended later in the life cycle of the web page, you need to use event delegation to attach event to dynamically appended elements.
Remove .val(), Use .attr() to get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
Try this:
jQuery("#target1").on("click", function() {
jQuery("#target_block").append('<div id="target2" data-rel-pid="12345">Click Me</div>');
});
jQuery("#target_block").on("click", '#target2', function() {
var bid = jQuery(this).attr("data-rel-pid");
alert(bid);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="target1">target1</div>
<div id="target_block">target_block</div>
You can use this code -
jQuery("#target2").on("click", function(){
var bid = jQuery(this).data("rel-pid");
});

javascript variable for jquery script

I dont know Javascript at all, so sorry for asking a question like this...
This is what I have:
$(document).ready(function(){$("#more0").click(function(){$("#update0").slideToggle("normal");});});
$(document).ready(function(){$("#more1").click(function(){$("#update1").slideToggle("normal");});});
$(document).ready(function(){$("#more2").click(function(){$("#update2").slideToggle("normal");});});
$(document).ready(function(){$("#more3").click(function(){$("#update3").slideToggle("normal");});});
$(document).ready(function(){$("#more4").click(function(){$("#update4").slideToggle("normal");});});
$(document).ready(function(){$("#more5").click(function(){$("#update5").slideToggle("normal");});});
$(document).ready(function(){$("#more6").click(function(){$("#update6").slideToggle("normal");});});
$(document).ready(function(){$("#more7").click(function(){$("#update7").slideToggle("normal");});});
$(document).ready(function(){$("#more8").click(function(){$("#update8").slideToggle("normal");});});
$(document).ready(function(){$("#more9").click(function(){$("#update9").slideToggle("normal");});});
$(document).ready(function(){$("#more10").click(function(){$("#update10").slideToggle("normal");});});
And So On.. Until #more30 and #update30...
So... Right now, my pages has 30 lines :)
Is there a way to do it less complicated?
Thanks!
Use attribute selector ^= . The [attribute^=value] selector is used to select elements whose attribute value begins with a specified value.
$(document).ready(function(){
$("[id^='more']").click(function(){
$("#update" + $(this).attr('id').slice(4)).slideToggle("normal");
});
});
Try to use attribute starts with selector to select all the elements having id starts with more , then extract the numerical value from it using the regular expression and concatenate it with update to form the required element's id and proceed,
$(document).ready(function(){
$("[id^='more']").click(function(){
var index = $(this).attr('id').match(/\d+/)[0];
$("#update" + index).slideToggle("normal");
});
});
use attribute start with selector
$(document).ready(function(){
$("[id^='more']").click(function(){
$("[id^='update']").slideToggle("normal");
});
});
//select all elements that contain 'more' in their id attribute.
$('[id^=more]').click(function(){
//get the actual full id of the clicked element.
var thisId = $(this).attr("id");
//get the last 2 characters (the number) from the clicked elem id
var elemNo= thisId.substr(thisId.length-2);
//check if last two chars are actually a number
if(parseInt(elemNo))
{
var updateId = "#update"+elemNo;//combine the "#update" id name with number e.g.5
}
else
{
//if not, then take only the last char
elemNo= thisId.substr(thisId.length-1);
var updateId = "#update"+elemNo;
}
//now use the generate id for the slide element and apply toggle.
$(updateId).slideToggle("normal");
});
Well first of all, you could replace the multiple ready event handler registrations with just one, e.g
$(document).ready(
$("#more0").click(function(){$("#update0").slideToggle("normal");});
//...
);
Then, since your buttons/links has pretty much the same functionality, I would recommend merging these into a single click event handler registration as such:
$(document).ready(
$(".generic-js-hook-class").click(function(){
var toggleContainer = $(this).data('toggleContainer');
$(toggleContainer).slideToggle("normal");
});
);
The above solution uses HTML Data Attributes to store information on which element to toggle and requires you to change the corresponding HTML like so:
<div class=".generic-js-hook-class" data-toggle-container="#relatedContainer">Click me</div>
<div id="relatedContainer>Toggle me</div>
I would recommend you to use Custom Data Attributes (data-*). Here You can store which element to toggle in the data attributes which can be fetched and used latter.
JavaScript, In event-handler you can use .data() to fetch those values.
$(document).ready(function () {
$(".more").click(function () {
$($(this).data('slide')).slideToggle("normal");
});
});
HTML
<div class="more" data-slide="#update1">more1</div>
<div class="more" data-slide="#update2">more2</div>
<div id="update1">update1</div>
<div id="update2">update2</div>
DEMO

Apply PHP script to a single text box

I'm after a simple answer I think.
I have a text box called 'ref' on a page.
When filled in and entered it takes the user to www.website.com/$ref.php.
I need their input to be uppercase to match the directory so I have added this code to change what they type.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("input").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
</script>
This works great but it is applied to all text boxes on the page.
How do I limit the script to text box 'ref' AND/OR is there a better way of achieving the same effect.
"if (textbox-name=ref) then apply script"
Thanks
Use the jQuery selector you already have:
$("input").keyup(function() {
Change it like this:
$('input[name="ref"]').keyup(function() {
that will select just that one text box and assign the keyup event to it.
jQuery selectors work just like css selectors.
However, if you want to insure that this is the only element that has this keyup function attached, then use an ID attribute.
Select the input by id,
$("#ref").
Your current code is applying the JQuery code to all input elements. To single out just that one, apply an id to the textbox, e.g. id="ref". Then you just reference it by id in your javascript:
$(document).ready(function() {
$("#ref").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
You should also read up on JQuery selectors.
What way did you call this text box 'ref'? if you have class="ref" as an attribute to it, change the selector in jQuery to input.ref. If you have id="ref", change it to input#ref. But you can better do it in php anyway (with strtoupper)

How do I change the value of an input element?

is it possible to "override/overwrite" an input element fixed value using javascript and/or jquery?
i.e. if i have an input element like this:
<div id="myDiv">
<input type="text" name="inputs" value="someValue" />
</div>
is it possible to make a jquery object of that element and then change its value to something else then rewrite the jquery object to the dom??
I'm trying but obviously I haven't got good results!
I've been trying something like this:
$('input').val("someOtherDynamicValue");
var x = $('input');
$("#myDiv").html(x);
If you just want to manipulate the value of the input element, use the first line of your code. However it will change the value of every input element on the page, so be more specific using the name or the id of the element.
$('input[name=inputs]').val("someOtherDynamicValue");
Or if the element had an id
$('#someId').val('some Value');
Check out jQuery's selectors (http://api.jquery.com/category/selectors/) to see how to get whatever element you need to manipulate with jQuery.
You can directly access the value via the $.val() method:
$("[name='inputs']").val("Foo"); // sets value to foo
Without needing to re-insert it into the DOM. Note the specificity of my selector [name='inputs'] which is necessary to modify only one input element on the page. If you use your selector input, it will modify all input elements on the page.
Online Demo: http://jsbin.com/imuzo3/edit
//Changes on the load of form
$(document).ready(function(){
$('#yourTxtBoxID').val('newvalue');
});
//Changes on clicking a button
$(document).ready(function(){
$('#somebuttonID').click(function(){
$('#yourTxtBoxID').val('newvalue');
});
});

Categories