Add number as parameter to function after I get button from DOM? - javascript

I use this row to get from DOM button:
var btn = parent.parent.document.getElementById('btnZoom')
I get from DOM this element:
<button type="button" id="btnZoom" onclick="parent.ExecuteCommand()" class="button_air-medium">
<img id="zoomMode" class="miniToolbarContant" src="...">
</button>
After I get the element from the DOM I need to add to ExecuteCommand function some number as parameter.
For example number 55:
<button type="button" id="btnZoom" onclick="parent.ExecuteCommand(55)" class="button_air-medium">
<img id="zoomMode" class="miniToolbarContant" src="...">
</button>
My question is how do I add number as parameter ExecuteCommand function afetr I get button from DOM?

Two ways to do that. One would be to set the number value as a separate data attribute on the HTML tag, and then have your parent.ExecuteCommand() command read it from there, via this:
var btn = parent.parent.document.getElementById('btnZoom');
btn.setAttribute('data-number', 55);
The other would be to add the onclick event handler in Javascript instead of using an attribute on the HTML tag:
<button type="button" id="btnZoom" class="button_air-medium">
var btn = parent.parent.document.getElementById('btnZoom');
btn.addEventListener('click', () => parent.ExecuteCommand(55));

Remember that onclick is an attribute and you can modify the value when you get the DOM element. Just like this:
var btn = parent.parent.document.getElementById('btnZoom');
btn.setAttribute("onclick","parent.ExecuteCommand(55)");

Related

Using Javascript Template Literals With The prepend() Method

I have a loop of button elements that are outputted with a while loop from data called from a MySQL database via PHP.
A user can add a button to this list and I want to add the new button and it's associated HTML using the prepend() method on the parent element, so it appears at the top of the list.
I know how to do this in various stages using createElement and adding class names and attribute names, but wondered if there is a simpler way of doing it using a template literal of the required HTML?
I've seen plenty of examples using parentElement.innerHTML(variableName), where variableName is the template literal, but these button elements illustrated below are inside a loop, and want I to prepend the newly created button to the parent .board-list element shown in the HTML.
When a new board name is submitted, a fetch() post request happens in the background to update the database, but I need to create a new element with JavaScript so this shows instantly to the user.
At the moment the template literal newButton is added to the HTML inside quote marks as a string of text, not as HTML DOM elements.
JavaScript
// added into the template literal below
const newBoardName = document.querySelector('.input-title').value;
const newButton = `
<button class="board-list-item full-width" name="board-name" type="submit">
<span>${newBoardName}</span>
<span class="add-icon flex">+</span>
</button>
`
document.querySelector(".board-list").prepend(newButton);
HTML
<div class="board-list">
// buttons outputted from the database appear here
</div>
<form>
<input class="input-title">
<button name="new-board-name">New Board Name</button>
<form>
I think a simple solution is to use .innerHTML, here is an example:
// added into the template literal below
const newBoardName = document.querySelector('.input-title').value;
const newButton = `
<button class="board-list-item full-width" name="board-name" type="submit">
<span>${newBoardName}</span>
<span class="add-icon flex">+</span>
</button>
`
let boardList = document.querySelector(".board-list");
boardList.innerHTML = newButton + boardList.innerHTML;
<div class="board-list">
// buttons outputted from the database appear here
</div>
<form>
<input class="input-title" value="user1">
<button name="new-board-name">New Board Name</button>
<form>
This is simply to answer your question, although it is not the best solution, so I do not see it recommended.
The solution to this was using the insertAdjacentHTML method. The question/answer given in one of the comments helped me on this, but I don't think it is a duplicate question, and the question linked to has an overly complicated answer IMHO.
// added into the template literal below
const newBoardName = document.querySelector('.input-title').value
const newButton = `
<button class="board-list-item full-width" name="board-name" type="submit">
<span>${newBoardName}</span>
<span class="add-icon flex">+</span>
</button>
`
// insert using 'afterbegin' to add as the first child element
document.querySelector(".board-list").insertAdjacentHTML('afterbegin', newButton)

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>"
>

Select div using jquery not working

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>');

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