how to add a unique id to a onclick event - javascript

I am having some code between pre tags and I want to catch al that code with an onclick event
My html structure is like below:
<div class="Message">
<div class="surroundpre">
<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, \\\'id1\\\')">[Select and Copy]</span>
<pre class="CodeBlock id="id22015640">
<!-- code goes her -->
</pre>
</div>
</div>
The pre elements and the div with class surroundpre is created by javascript.
The unique id for the pre:
$('pre').each(function(){
if ($(this).attr('id') == undefined){
$(this).attr('id','id'+Math.floor((Math.random() * 99999999) + 1))
}
});
The div with surroundpre is created like below:
$('.Message .CodeBlock', this).wrap('<div class=surroundpre></div>');
The span is created with php variable:
$SelectButton = '<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, \\\'id1\\\')">[Select and Copy]</span><br />';
in combination with:
$('.surroundpre').prepend('$SelectButton');
My question: the id1 in the php variable should be replaced with the same unique id as in the pre tag.
How can I achieve this?
Or is there an other method to achieve this?

This might work for you, make a few changes, first in PHP:
$SelectButton = '<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, this.getAttribute(\"data-block-id\"))">[Select and Copy]</span><br />';
Then in JS:
$('pre').each(function(){
var id;
if ($(this).attr('id') == undefined){
id = 'id'+Math.floor((Math.random() * 99999999) + 1);
$(this).attr('id',id);
$(this).prev('span').attr('data-block-id',id);
}
});
Now the id generated in js is attached to the span at the same time of creation, when it is available to you, and the pregenerated (in PHP) onclick event can access it when it needs it (as long as that is after the ID setting code has run).

Related

Retrieve name value from button in javascript

I have the following HTML:
<div class="dropdown" data-offers-filter-segments="">
<button class="toggle--dropdown" name="toggle-segment-cagetories-list">
<span class="dropdown__label" id="dropdown__labelAllCategories">All Categories</span>
</button>
<div class="dropdown__content" hidden="hidden">
Which renders a dropdown, when clicked a new class is appended which is called is-dropped so the parent div will look like this once its been clicked on class="dropdown is-dropped"
Now using Javascript I'm trying to retrieve name="toggle-segment-cagetories-list" which we will use within DTM (Adobe Tag Manager) as an eVar value but I'm uncertain how I go about retrieving that name value, so far I have the following javascript:
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
if(hasClass(document.getElementsByClassName('dropdown')[0], 'is-dropped')){
// Now get the name value ?
}
else {
alert("false");
}
Now I'm pretty new to javascript so if someone can shed some light in how I go about getting the name value and passing it to DTM I would highly appreciate it.
use document.querySelector:
<div class="dropdown is-dropped" data-offers-filter-segments="">
<button class="toggle--dropdown" name="toggle-segment-cagetories-list">
<span class="dropdown__label" id="dropdown__labelAllCategories">All Categories</span>
</button>
<div class="dropdown__content" hidden="hidden">
<script>
var button=document.querySelector('div.is-dropped button.toggle--dropdown');
var name=button&&button.name||'';
alert(name);
</script>
if you want to use your own data-attributes, you need start your attribute name with 'data':
<button class="toggle--dropdown" data-name="toggle-segment-cagetories-list">
In order to retrieve the value of the attribute, you can do as shown in the example below:
var article = document.getElementsByClassName('toggle--dropdown');
article[0].dataset.name // article[0] because getting elements by className returns an array

Jquery 'find' not working with data tag

I'm struggling to get the Jquery 'find' to work in the following code. I've stripped it down to the very basics. In short, what I'm trying to achieve is, I have two lists containing the same names. When the name is clicked on the top list, I want a more detailed box to toggle open below. Then when either is clicked again, the lower box will toggle closed again.
I assume something is wrong in the Jquery with the 'find'. The other part, which collects the ID works fine when the ID is sent to an alert.
I've looked through other answers and that find section is from another answer but it doesn't work in this example, so presumably I'm doing something wrong on some other level.
Bear in mind that just finding the div or paragraph element won't work for my full code. I've just put them in those tags for this example. I basically need to find (in this example), the para inside the correct div (obviously there's only one div here but loads in my full code).
<html>
<body>
<?php
for ($x=0; $x<10; $x++) {
echo "<p class = 'player_name' data-playerid = $x>Player $x</p>";
}
echo "<div class = 'individual_player_reports'>";
for ($x=0; $x<10; $x++) {
echo "<p class = 'player_name' data-playerid = $x>Player $x</p>";
}
echo "</div>";
?>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$('.player_name').on('click',
function() {
var id = $(this).data().playerid;
$('.individual_player_reports').find("[playerid='" + id + "']").toggle();
});
</script>
</body>
playerid !== data-playerid
Data attributes are just like any other attributes. Use the full name of the attribute when using the attribute equals selector.
$('.player_name').on('click',function() {
var id = $(this).data().playerid;
$('.individual_player_reports').find("[data-playerid='" + id + "']").toggle();
});
$('.player_name').on('click',function() {
var id = $(this).data().playerid;
$('.individual_player_reports').find("[data-playerid='" + id + "']").toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="player_name" data-playerid='1'>1</p>
<p class="player_name" data-playerid='2'>2</p>
<p class="player_name" data-playerid='3'>3</p>
<div class="individual_player_reports">
<p data-playerid='1' style="display: none;">1</p>
<p data-playerid='2' style="display: none;">2</p>
<p data-playerid='3' style="display: none;">3</p>
</div>
As #T.J. Crowder suggests, you don't need to use .data() in this case, it would be more efficient to skip .data and just get the attribute value directly to avoid initializing the data cache unless you are using .data()'s features elsewhere too.
var id = $(this).attr('data-playerid');

Use button to setAttribute and display it within span tag

I am trying to create a real-world example of get and set data attribute.
so I created a simple div that contains the data-email attribute and set a default one.
Now what I want to attain is when I click on the button it will change the default attribute to the set attribute on my JavaScript codes.
Currently I also don't know how can I show the data attribute value inside tag of my div.
here's my markup:
<div id="my-id" data-email="youremail#email.com">Sam's email is <span> "Show Email Here" </span> </div>
<button type="button" id="btn-id" onclick="click-btn()">Set Attribute Now</button>
here's my JavaScript:
var email = document.getElementById('my-id');
var emailget = email.getAttribute('data-email');
var button = document.getElementById('btn-id');
function click-btn(){
emailset = email.setAttribute('data-email', newemail#email.com);
}
here's the JSFIDDLE link: http://jsfiddle.net/jypb2jdg/6/
Any idea?
As #adeneo suggested we should not use hyphen in function name as it may be interpreted as minus sign, so remove and you may use like this:
You need to use quote in setAttribute value:
function clickBtn(){
emailset = email.setAttribute('data-email', 'newemail#email.com');
//^^ here ^^
}
You need something like this:
function clickBtn(){
emailset = email.setAttribute('data-email',
email.getAttribute('data-email') || 'newemail#email.com');
}
First thing is that the email you've written must be within quotes.
<div id="my-id" data-email="youremail#email.com">Sam's email is <span id="my-span-id"> "Show Email Here" </span> </div>
<button type="button" id="btn-id" onclick="click_btn()">Set Attribute Now</button>
The JS code:
function click_btn(){
var email = document.getElementById('my-id');
var emailContainer = document.getElementById("my-span-id");
var emailget = email.getAttribute('data-email');
emailContainer.innerText = emailget;
emailset = email.setAttribute('data-email', "newemail#email.com");
}
The code can be found in:
http://jsfiddle.net/jypb2jdg/17/
Some point I want to mention:
Include the JS before the div. Because button will not recognize click_btn() function before its declaration;
Do not use '-' symbol for function names in JS.
You could write a script without using ID for span. It will need additional structs (finding child elements, figuring out which one is what you need, set its' innertext.
You need to keep in mind that functions in javascript cannot have hyphens in their name as it is treated as a mathematical operator. Rest is just plain DOM manipulation :
<div id='my-id' data-email="youremail#email.com">Sam's email is <span id="mail"> "Show Email Here" </span>
</div>
<button type="button" id="btn-id" onclick="clickbtn()">Set Attribute Now</button>
jS:
var em;
window.onload = function(){
em = document.getElementById("my-id");
document.getElementById("mail").innerHTML = em.getAttribute("data-email");
};
function clickbtn(){
var old_mail = em.getAttribute("data-email");
em.setAttribute("data-email","newmail");
document.getElementById("mail").innerHTML = em.getAttribute("data-email");
}
Fiddle : http://jsfiddle.net/dndnqygL/4/
Note : instead of assigning a new id to the span you can also use the element.firstChild property to set the innerHTML.

javascript: use getElementByID to populate multiple divs

is there a way to write the same thing clientside using javascript to multiple divs or multiple spots on a page?
I have a php script outputting rows from a database. To edit the contents, I would like to insert a checkbox before each row as with the iphone edit contacts and to do it quickly, I'm trying to use javascript to populate a div with a checkbox before each row using getElemenByID.
One problem is you cannot have more than one div of the same name on a page so I can't write once and have it populate multiple divs of the same name. If I give divs different names than I have to write multiple times which is not appealing especially as the number of rows may vary.
As a related question would checkboxes inserted using javascript even work?
Here is non working code:
js
function edit() }
var box = '<input type="checkbox name=num[]>';
var target = "checkbox";
document.getElementById(target).innerHTML = box;
return;
}//end function
html (generated by PHP from dbase)
<form action="edit.php" method="post">
<a href="javascript:void" onclick="edit()";>edit</a>
<div id="checkbox"></div>Row1 contents<br>
<div id="checkbox"></div>Row2 contents<br>
<form type = "submit" value="Edit">
</form>
Does anyone know a way to do this ie make boxes appear that can then be selected for submission?
Many thanks for any suggestions.
Should be generated using PHP instead, but...
HTML
I'm guessing that you want to use a span element (not a div) for your checkbox placeholder, otherwise you'd have a checkbox on one line, and then "Row1 contents" below the checkbox, versus having the checkbox next to the text.
[X]
Row 1 Contents
versus (span)
[X] Row 1 Contents
<form action="edit.php" method="post" name="frmRows" id="frmRows">
edit
<span class="checkbox"></span>Row1 contents<br>
<span class="checkbox"></span>Row2 contents<br>
<input type = "submit" value="Edit">
</form>
JavaScript
It's not recommended to use .innerHTML in JavaScript unless absolutely necessary (not supported in all browsers, and there are better ways to accomplish the same task.)
function edit() {
var newCb;
var i;
var checkboxList = document.getElementsByClassName( 'checkbox' );
for ( i = 0; i < checkboxList.length; i++ ) {
newCb = document.createElement( 'input' ); // Create a new input element
newCb.setAttribute( 'type', 'checkbox' ); // Set attributes for new element
newCb.setAttribute( 'value', 'SomeValueHere' );
newCb.setAttribute( 'name', 'checkboxName' );
newCb.setAttribute( 'id', 'checkbox-' + i );
checkboxList[i].appendChild( newCB ); // Add checkbox to span.checkbox
}
}
The ID attribute must be unique on each page. You could use the class attribute like this:
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
and then you can use
var check = getElementsByClassName('checkbox');
for (var i=0; i< check.length; i++) {
check[i].innerHTML = box;
}
But... this will not work in IE < 9. If you are using a framework like jQuery they already implemented a workaround for this but with pure JS you have to implement this yourself.
jQuery example
HTML
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
JS
var box = '<input type="checkbox" name="num[]" />';
$(".checkbox").html(box);
The HTML
The first thing to do is to update the generated HTML. In HTML element id attributes should be unique just like field names inside a form. To classify multiple elements as similar you should use the class attribute.
Here is an example of how you could structure the HTML.
<form action="edit.php" method="post">
edit
<div id="row1Identifier" class="editCheckbox"></div>Row1 contents</br>
<div id="row2Identifier" class="editCheckbox"><?div>Row2 contents</br>
<input type="submit" value="Submit">
</form>
The javascript
Using document.getElementsByClassName will return a list of elements with the matching class.
​function edit () {
// set up the variables used in this function
var checkboxDivs = document.getElementsByClassName('editCheckbox'),
i,
loopDiv;
// make the change to each div
for (i = 0; i < checkboxDivs.length; i += 1) {
loopDiv = checkboxDivs[i];
loopDiv.innerHTML = '<input type="checkbox" name="' + loopDiv.id + '">';
}
}​
Even if you could do it with a single line (using jQuery, for exemplo), you would actually be running a loop through all the divs (that's the only way to change something in various elements: change it in each one).
So you can do this with pure JavaScript using a loop to run the modifications in all the divs, getting them by id (the faster way):
for(var i = 0; i < numberOfDivs; i++){
document.getElementById("myElement" + i).innerHTML = box; //concatenating i to a base id
}
You could also use another slower techniques to get elements by tag name or class, or even use a lib such as jQuery.
If you use jquery:
function edit() {
// box = '<input type="checkbox name=num[]>';
var target = "checkbox";
$(".cb").html(box);
return;
}//end function
<form action="edit.php" method="post">
edit
<div class="cb" id="checkbox">aa</div>Row1 contents<br>
<div class="cb" id="checkbox">bb</div>Row2 contents<br>
</form>

JQuery: Selecting elements with unique class AND id

I have this html code:
<div class="category" id="154"> Category </div>
<div class="category2" id="156"> Category2 </div>
<div class="category3" id="157"> Category3 </div>
<div class="category4" id="158"> Category4 </div>
<input type="text" />
So in example if I write a id in text box, how to select div .category with this ID and get inner HTML text. With jQuery
so you only need to use the ID as this is a unique value (or should be)
var html = $("#154").html();
NOTE: If you do have duplicate ID values in use then it is important to note that JQuery will only select the first one.
if you want to do this when a textbox value is entered you could do this on the textbox change event...
$("input").change(function(){
var id = $(this).val();
var element = $("#" + id);
if(element){
var html = element.html();
//do something with html here
}
});
NOTE: you may want to put an ID value on your textbox to ensure you get the correct control
Although I strongly suggest you find a way around using duplicate ID values, you could have a function like this to get the DIV you want...
function GetContent(className, id) {
var result = null;
var matchingDivs = $("." + className);
matchingDivs.each(function(index) {
var div = $(matchingDivs[index]);
if (div.attr("id") == id) {
result = div.html();
}
});
return result;
}
Click here for working example
I recommend you give the textbox an ID, in case you add other textboxes to the page.
But if you only have the 1 text input, the following would work:
var id = $('input:text:first').val();
var innerHtml = $('#' + id).html();
Here is a jsFiddle that will alert the html using this technique whenever the text in the textbox changes.
$("#id.class")
will select the necessary element by both class and ID (replacing id and class with their respective names, of course).
Adding .html() to the end will get you the content.
i.e:
$("#id.class").html()

Categories

Resources