Select div using jquery not working - javascript

I have an event listener on dynamically created elements:
<script>
$(document).on('change', '.inputfile', function() {
var name = ($(this).val().split('\\').pop());
selectFile(name);
});
</script>
Once file is selected, i would like to append a paragraph showing the filename itself. My problem is that jquery selector is not working:
function selectFile(filename) {
alert(filename);
var classes = $(this).closest('.inputgroup');
$('classes').append('<p>'+filename+'</p>');
}
I would like to append the paragraph in the nearest div with class=inputgroup, because there are several div with that class.
Using a simple $('.inputgroup').append('<p>'+filename+'</p>'); is ok and paragraph is created.
This is the HTML:
<div class="inputgroup">
<label class="btn btn-default btn-info" style="margin-top: 8px">
Browse <input type="file" style="display: none;" class="inputfile"/>
</label>
<button type="button" class="btn btn-outline-danger" onclick="myAjax()">Ok</button>
<span id="remove_field" class="glyphicon glyphicon-remove" aria-hidden="true" style="vertical-align: middle"></span>
</div>

This line
$('classes').append('<p>'+filename+'</p>');
Is searching for an element named "classes" - that's not a valid HTML element.
I think you wanted
$(this).closest('.inputgroup').append('<p>'+filename+'</p>');
Based on this line of your question
I would like to append the paragraph in the nearest div with class=inputgroup
But you should put this straight in the event handler, otherwise this has a different meaning
$(document).on('change', '.inputfile', function() {
var name = ($(this).val().split('\\').pop());
$(this).closest('.inputgroup').append('<p>'+name+'</p>');
});

In this line of code
var classes = $(this).closest('.inputgroup');
$('classes').append('<p>'+filename+'</p>');
The first line gives you an jQuery object. Which you can directly use to append the p tag.
As already mentioned in other answer your second line looks for a element named classes which does not exist.
So simply use the Jquery object you have and append the paragraph. Like below
classes.append('<p>'+filename+'</p>');

Related

jquery .length providing individual counts in the log, not the total [duplicate]

I have 3 buttons with same ID. I need to get each button's value when it's being clicked.
<button id="xyz" type="button" class="btn btn-primary" value="1">XYZ1</button>
<button id="xyz" type="button" class="btn btn-primary" value="2">XYZ2</button>
<button id="xyz" type="button" class="btn btn-primary" value="3">XYZ3</button>
Here is my current jQuery script:
$("#xyz").click(function(){
var xyz = $(this).val();
alert(xyz);
});
But it works only for the first button, clicking on the other buttons are being ignored.
I have 3 buttons with same id ...
You have invalid HTML. You can't have more than one element in a page with the same id attribute value.
Quoting the spec:
7.5.2 Element identifiers: the id and class attributes
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
Solution: change from id to class:
<button type="button" class="btn btn-primary xyz" value="1">XYZ1</button>
<button type="button" class="btn btn-primary xyz" value="2">XYZ2</button>
<button type="button" class="btn btn-primary xyz" value="3">XYZ3</button>
And the jQuery code:
$(".xyz").click(function(){
alert(this.value);
// No need for jQuery :$(this).val() to get the value of the input.
});
But it works only for the first button
jQuery #id selector docs:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
If you look at the jQuery source you can see when you call $ with an id selecor-($("#id")), jQuery calls the native javascript document.getElementById function:
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
}
Though, in the spec of document.getElementById they didn't mention it must return the first value, this is how most of (maybe all?) the browsers implemented it.
DEMO
ID means "Identifier" and is valid only once per document. Since your HTML is wrong at this point, some browsers pick the first, some the last occuring element with that ID.
Change ids for names would be a good step.
Then use $('button[name="xyz"]').click(function(){
From my experience, if you use $('button#xyz') selector instead it will work. That's a hack, but it's still invalid HTML.
Although changing the id's to a class is better, you can get all the elements with the same id using the attribute equals selector:
$('[id="xyz"]')
Or this to get only buttons with id xyz:
$('button[id="xyz"]')
Or divs with id xyz:
$('div[id="xyz"]')
etc.
Alternatively you could use the "Attribute Contains Selector" to get all elements with ids that contain "xyz":
$('[id*="xyz"]')
Of course, this means all elements with id that partially contain "xyz" will get selected by this.
this also worked if you have multiple element with same id.
$("button#xyz").click(function(){
var xyz = $(this).val();
alert(xyz);
});
you can check HERE
If you have same id in a container you can use on() to access each element for every event
$("#containers").on("click","#xyz",function(){
alert($(this).val())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="containers">
<button id="xyz" type="button" class="btn btn-primary" value="1">XYZ1</button>
<button id="xyz" type="button" class="btn btn-primary" value="2">XYZ2</button>
<button id="xyz" type="button" class="btn btn-primary" value="3">XYZ3</button>
</div>
and info about on() is here
You can't have the same id because id is unique in page HTML. Change it to class or other attribute name.
$('attributename').click(function(){ alert($(this).attr(attributename))});

Select the custom tag from button attribute

I have created a button element structure like below
<input
type="button"
class="btn btn-primary"
name="redirect"
value="<mycustomtag data-id=15>"
title="<mycustomtag data-id=14>"
>
Now, whenever the DOM gets ready I'm trying to find out the custom element and trying to replace with string. But I'm not able to replace the custom element.
The snippets I have used to find is as below
jQuery("mycustomtag").each(function(){
//process here
});
PS this works fine in the following case:
<div><mycustomtag data-id=20></div>
<h4><mycustomtag data-id=18></h4>
your code
jQuery("mycustomtag")
will try to find tag named mycustomtag, and what i understand is you are trying to replace the input attributes right ?
try following
//if you want to get values
var value = $("#btnCustom").attr("value");
var title = $("#btnCustom").attr("title");
alert(value);
alert(title);
//if you want to set values
$("#btnCustom").attr("value","replacevalue");
$("#btnCustom").attr("title","replace value 2");
value = $("#btnCustom").attr("value");
title = $("#btnCustom").attr("title");
alert(value);
alert(title);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input
type="button"
class="btn btn-primary"
name="redirect"
value="<mycustomtag data-id=15>"
title="<mycustomtag data-id=14>"
id="btnCustom"
>
You couldn't find them since the value of an attribute is considered just like a string.
To find those elements you need to select them based on the main tag by selecting the specific attribute using .prop(), like :
$('input').each(function() {
$(this).val();
$(this).prop('title');
});
PS this works fine in the following case
That because in this case it's considered as a tag element in your DOM that why jQuery can find it by a simple selector.
$('input').each(function() {
console.log($(this).val());
console.log($(this).prop('title'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btn btn-primary" name="redirect" value="<mycustomtag data-id=15>" title="<mycustomtag data-id=14>">
In your first HTML code what you're looking for is in the value or title attribute. In your second it's the element name.
To select an element based on its value, use the following syntax:
$("input[value='<mycustomtag data-id=15>'")
To select an element based on its title works similarly.
If you put your custom tag in an attribute of another tag it won't be rendered in the page, in other words it won't be part of the document DOM tree, it will be just a string in an attribute, that's why when you use jQuery("mycustomtag") you don't get anything, but it will work if you put it as a child of a div or a span.
So in your specific case you will need to use .attr() method to get it from this specific attribute or .val() method if it's in the value.
jQuery("input").attr("title");
jQuery("input").val();
Demo:
console.log(jQuery("input").attr("title"));
console.log(jQuery("input").val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input
type="button"
class="btn btn-primary"
name="redirect"
value="<mycustomtag data-id=15>"
title="<mycustomtag data-id=14>"
>

get input attribute on button click

I have a page with mutiple inputs,each input has a button. is there anyway of getting the inputs value on button click, without hardcoding the inputs id?
.prev doesnt work as there is a span directly after input
example
js
$('button').click(function () {
var inputcontent = $(this).prev('input').attr('id');
console.log(inputcontent);
});
html
<input type="text" id="1">
<span class="input-group-btn">
<button type="button">Go!</button>
</span>
You need to use .parent() here since input is the immediate previous sibling of parent <span> of the button:
var inputcontent = $(this).parent().prev().attr('id');
Fiddle Demo
Side note: id started with number is invalid HTML4 markup. Reference

Button value is empty when use jquery selector

i am trying to select value for the selected button like the following :
html code :
<div class="span3">
<div>DEBIT/CREDIT</div>
<div class="btn-group" data-toggle="buttons-radio" id="investadjust-debitcredit-button">
<button name="debitCredit" type="button" id="credit-button" class="btn active" value="CREDIT" >CREDIT</button>
<button name="debitCredit" type="button" id="debi-button" class="btn" value="DEBIT" >DEBIT</button>
</div>
</div>
javascript code :
$("#investadjust-debitcredit-button>.active").val()
but i get only empty when i printed the above line after selecting one button.
what could be the reason.
you need to place your code in
$(document).ready(function(){
// your jquery code
});
As neo said you need to place your code in document ready function and use the class name of the button without spaces or you can add underscore between the words as well like this:
<button name="debitCredit" type="button" id="credit-button" class="btn_active" value="CREDIT" >CREDIT</button>
So, the code goes like:
$(document).ready(function(){
alert("value "+$("#investadjust-debitcredit-button>.btn_active").val());
});
Good Luck!

Have multiple buttons with same attributes (class, type, value, etc) that can "point out" their parent DIV when called?

I'm having some trouble figuring this out. I want to make it so I can place a button in a number of different DIVs but have all the info for the button be the same (class, type, value, etc), this is because its an edit button for the DIV so its just something that is automatically included with any new DIV that is created and my server-side app will generate these buttons automatically. So the issue is how to get the ID of the parent DIV, and I am having some trouble with this as it seems to always default to DIV upd1 even when I click the button contained within upd2, I've been searching on this but everything I have found so far hasn't led me out of this issue.
<div id="upd1">
<input id= "button" class="button" type="submit" value="Click to edit this Panel" />
</div>
<div id="upd2">
<input id= "button" class="button" type="submit" value="Click to edit this Panel" />
</div>
then I have:
$("#button").click(function() {
dividediting = $("#button").closest("div[id^='upd']").attr("id");
alert(dividediting);
});
Try this:
$(".button").click(function() {
var dividediting = $(this).parent().attr('id');
alert(dividediting);
});
You cannot have two items with the same id - you have to be using a class not the same id on each button.
You need a .class selector for your buttons instead, like this:
$(".button").click(function() {
dividediting = $(this).closest("div[id^='upd']").attr("id");
alert(dividediting);
});
#button is an #ID selector that searches for an id="button" instead of a class="button" like you want. Also you want $(this) inside the handler, so you're getting the closest <div> of the clicked element, not the first matched .button element.
first of all, why are you using $("#button") i didn't see any id="button" in your DOM, secondly, you can use this
var dividediting = $(".button").parent().attr("id");
alert(dividediting);

Categories

Resources