i am trying to alert id of a button (which is generated using jquery ) but when i alert its value it not coming right. heres the code
function removeimg(name,btn12){
//make request to remove the name
// $("#" + name).closest('li').remove();
// $("#" + btn12).remove();
// document.getElementById(name).style.display = 'none';
// document.getElementById(btn12).style.display = 'none';
var str = "#" + btn12;
alert(str);
alert($(str).val());
}
here is the link
http://shri-ram.lifekloud.com/pilot/step4.php
when you uplaod a image under the tab "add delete photo" the button is generated
i am trying to alert id of a button
val() does not get the id of an element; val returns the value element.
To get the id of an element, use attr
alert($(str).attr('id'));
Just a stab in the dark from your comment well its not even returning value thts the issue. but the id name is getting displayed correctly
If you have
<input type='button' id='b' value='btn' />
then
alert($('#b').val());
will in fact display btn. That said, if you have
<button id='b'>btn</button>
then nothing will be displayed. But like I said that's just a stab in the dark. It's impossible to know better without the html available (and I'm afraid I don't have time to parse through your site)
You have one meta-character . in your id #btnheader-8878374.png, That is the problem.
Just escape like this
$('.#btnheader-8878374\\.png')
and try you will get your concept working.
Full code,
var str = "#" + btn12;
str = str.replace('.','\\\\');
alert($(str).val());
Your problem is most likely that you do not have the value attribute set on your buttons, thus calling val() returns nothing.
If you want the text of the button just call text().
See jsFiddle
HTML
<button id="btn12">Button 12</button>
JQUERY
var str = "#" + "btn12";
alert( str ); // yields #btn12
alert( $(str).val() ); // yields nothing
alert( $(str).text() ); // yields Button 12
Related
I have Bootstrap Table that contains an edit button on each row. I've used a data formatter to make the pass the id of the record over with a data attribute that can be extracted when clicked. When I inspect the element in the console I can see the ID is in the dataset property, but when I try to get it out using element.dataset the console contains an error telling me that the dataset is undefined. It's frustrating because I can see it's there!
Here's my click event:
$(".job-edit").click(function(event) {
var editModal = $("#jobEditModal");
var clicked = $(event.target);
var id = clicked.dataset.jobid;
console.log(id);
event.stopPropagation();
//editModal.modal();
});
And the formatter that sets the button up:
job.editFormatter = function (value) {
return "<button class='btn job-edit text-center' data-jobId='" + value + "'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Edit</button>";
}
So far I've tried replacing .dataset with .getAttribute(), but that didn't work either, I've also tried changing the casing of jobid to jobId, past that I'm not sure what could be causing the problem.
instead of using dataset you can directly get the jobid by using .data() method of jquery like below.you are getting undefined value for dataset as the clicked variable is a jquery object which does not have a definition for dataset
$(".job-edit").click(function(event) {
var editModal = $("#jobEditModal");
var id = $(this).data("jobid");
console.log(id);
event.stopPropagation();
//editModal.modal();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn job-edit text-center' data-jobId='2'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Edit</button>
Your issue is because clicked is a jQuery object which has no dataset property.
To fix this you need to use the native element reference:
var id = e.target.dataset.jobid;
Alternatively, use the data() method of the jQuery object:
var id = clicked.data('jobid');
Below is a function where it controls whatever happens after a file has finished uploading in its own table row. Each table row consists of a file input where the user can upload a file and then the name of the file is appended within it's own table row.
If the upload was successful then it displays a successful message, if upload was not successful then it displays a message stating there is an error. But I also have another function within the function where the user can delete a file by clicking on the "Delete" button. The only problem I have is with this line of code:
$(".imagemsg" + counter).html(data);
Let's say that I have 2 table rows, and I delete a file in the first row, the message within .imagemsg should only be displayed in the first row as that was the row the deletion occured, it shouldn't display the message in the first and second row.
Another example is that if I have 4 table rows and I delete the file in the third row, then the message should be displayed in the 3rd row as that is where the deletion has occured.
So my question is what do I need to add to $(".imagemsg" + counter).html(data); so that the message is only displayed within the row the deletion of the file occured and not in all .imagemsg which is in every row?
Below is full code:
function stopImageUpload(success, imagefilename){
var result = '';
var counter = 0;
counter++;
if (success == 1){
result = '<span class="imagemsg'+counter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
var image_file_name = $(this).attr('image_file_name');
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
.done(function(data) {
$(".imagemsg" + counter).html(data);
});
$(this).parent().remove();
});
return true;
}
BELOW IS HTML CODE:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='listImage' align='left'></p>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
I believe that your counter variable will always be 1. So, all your span.imagemsg1 are the same. This is why you get the message in every row. Set the counter outside the function to increment the counter.
I believe that will stop the behavior that you are seeing, but I would like to give a shout out to the other answers as they are giving good advice to cleaning this code up.
Frankly, you should never use unique identifier in the class. Why not use an id or a data-image-count attribute?
In your html code you'll need to add a unique identifier, I would suggest using id. This way when you try to reference the element to add the error message in, it will only find one element. Currently it's looking for the first occurrence of the element with class = "imagemsg". You'll need a way to loop through each "row" and make the id's "imagemgs1", "imagemsg2", etc...Hope it helps.
It would be helpful to be able to see the HTML. Also, I cannot see in your script what you do with the "result" value. At this stage, I personally don't think there is enough info to help satisfactorily you yet.
However, an issue you will undoubtedly see is with your "counter" variable. Maybe that is your problem - hard to tell without the detail I asked for above. Your jQuery.ajax call will complete at some point but the value of "counter" may not be the same as when you called the jQuery.ajax() method. This is because the "counter" variable is being declared in a different scope.
E.g. Look at the code below. It sort of demonstrates your problem with the counter variable. It may look like at the end of 5 seconds it will spit out the numbers from 1 to 10 but it won't. It will spit out the value "10" ten times.
var x = 0;
for (var i = 0; i < 10; i++)
{
x++;
setTimeout(function() { console.log(x); }, 5000);
}
This problem applies to your code as well. You can fix the above by copying the variable value in to a variable of your local scope. E.g.:
var x = 0;
for (var i = 0; i < 10; i++)
{
var newScope = function() {
x++;
var y = x;
setTimeout(function() { console.log(y); }, 5000);
}();
}
html file:
<div id ="main">
</div>
Javascript:
//create a div
var divElem = $('<div class="divText"></div>');
//create input element inside it
var inhtml = "<input type='text' id='12345' />";
//add to page
$(divElem).html(inhtml).appendTo('#main')
Following does not work as it is unable to find input element:
//retrieve input element
$('#12345').val('hello')
Following works:
document.getElementById('12345').value = 'hello'
Following works:
var ipElem = $(inhtml);
$(divElem).append(ipElem).appendTo('#main')
$(ipElem).val('hello')
Can anyone tell why first version of retrieving element does not work in jquery? (just starting with jquery... :) )
Edit:
I think '12345' works but not some weird id like: mytext0.15942923246580176
See here:
http://jsfiddle.net/9PVNb/4/
You're wrapping divElem in jQuery object twice:
var divElem = $('<div class="divText"></div>');
var inhtml = "<input type='text' id='12345' />";
$(divElem).html(inhtml).appendTo('#main') // Nop '$(divElem)' plus missing `;`
divElem.append(inhtml).appendTo('#main'); // Yup
EDIT:
Edit: I think '12345' works but not some weird id like: mytext0.15942923246580176
Your code at http://jsfiddle.net/9PVNb/4/ isn't working because:
// Your `id` has a `.` which you didn't escape
var elemid = 'mytext0.15942923246580176';
You can make it work by doing this:
alert($('#' + elemid).val()); //undefined. DOES NOT WORK
alert($('#' + elemid.replace('.', '\\.')).val()); // hello world IT WORKS!
works here: http://jsfiddle.net/xvKcd/
basic check:
are you using $(document).ready()? your code may be firing up before the element you needed was loaded.
did you load jQuery before anything else?
typos?
I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product
Those snippes of code that you will check works fine for FF, Chrome, Safari, but seems to be a problem with IE when running jQuery clone function:
My template:
<form method="post" action="/post/add/">
{{ form.management_form }}
<div class='table'>
<table class='no_error'>
<input id="id_mypost_set-0-title" type="text" name="mypost_set-0-title" />
<input id="id_mypost_set-0-content" type="text" name="mypost_set-0-content" />
</table>
</div>
<input type="button" value="Add Other" id="add_more">
<script>
$('#add_more').click(function() {
cloneMore('div.table:last', 'mypost_set');
});
</script>
</form>
In a javascript file:
function cloneMore(selector, type) {
var newElement = $(selector).clone(true);
var total = $('#id_' + type + '-TOTAL_FORMS').val();
newElement.find(':input').each(function() {
var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
});
newElement.find('label').each(function() {
var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
$(this).attr('for', newFor);
});
total++;
$('#id_' + type + '-TOTAL_FORMS').val(total);
$(selector).after(newElement);
}
The problem is with the selector: "A clone of the original html piece of code works OK", but, A clone from cloned piece of code marks the selector as "undefined", in other words, the second time that I clone the table the selector doesnt work anymore for those cloned items.
Problem only for IE.
What im missing? Any hint is apreciated :)
This is a known jQuery bug, though they claim it is fixed.
One option here is to use .html(), and clone them manually. This will not clone events and saved .data, which may be an issue for you. .live can help if you have events here.
If the only thing you need is to change the names and id, a better option is to use a regular expression (this clones the events from the first element, mind you):
var name = $(this).attr('name').replace(/-\d+-/,'-' + total + '-');
this will search for -number-, and replace it, so it finds the last number on all browsers, or -0- on IE.
Here's a working demo with alerts: http://jsbin.com/evapu
As a side note - your code is a little messy. jQuery code should be inside $(document).ready (the click), you have a table with no body (no <tr>,<td> - the inputs are thrown out), and the code has some duplications.
Although it didn't help in this case, invalid DOM and not using the ready event can cause problems.
you're missing a hidden input with id 'id_' + type + '-TOTAL_FORMS'
- you're getting your total from this object and using it to modify the name and id of cloned objects.
I tried your code with this:
<input type="hidden" id="id_mypost_set-TOTAL_FORMS" value="1"/>
added right after
<form method="post" action="/post/add/">
and it works correctly, all new inputs have correct ids.
does this really work in FF ??
You code works perfectly on all browsers as stated before
Still if you could replace:
var newElement = $(selector).clone(true);
with:
var newElement = $($(selector).html());
and see if it helps.
Also, re-attach the event handler, like so.
newElement.bind(EVENT, function() {});
Or use the appropriate helper.
perhaps you can use this clone function :
/*
* Clone method
* Prevents reference problem
*/
clone: function( obj ){
if(obj == null || typeof(obj) != 'object')
return obj;
var temp = new obj.constructor();
for(var key in obj)
temp[key] = clone(obj[key]);
return temp;
}