Reputation: 23
I'm pretty young and new to here so please bear with me. I am making a site and I am trying to create html links output in javascript. I am currently trying this method but it is not working? I am trying to change the 'mything' to show this text and add a link.
The code in javascript where I try to add a button is
document.getElementById('mything').innerHTML = place.name+' '+' <button id="edit" type = "button" class = "btn btn-link">(edit)</button>';
The bit for button is
$('#mything').on('click', function() {
$('#stuff2').hide();
})
I hope I have put this in right? Thankyou
Upvotes: 0
Views: 61
Reputation: 13437
Here's my attempt at illustrating what I think you're getting at:
var place = {
name: 'Japan'
};
var span = document.getElementById('mything');
span.innerHTML = place.name + ' <button id="edit" data-place="' + place.name + '">(edit)</button>';
span.querySelector('button').addEventListener('click', function(e){
var place = this.getAttribute('data-place');
alert(place);
});
<span id="mything"></span>
Upvotes: 1
Reputation: 3761
Using your code, this is what happens. I've commented the code up. Is this what you EXPECT to happen?
// Not sure what the place.name was coming from,
// created a stub object to field that.
place = {
name: "Foo"
};
// USe this to create the button, then create the
// event listener ON the button.
// This uses the browser getElementById...
document.getElementById('mything').innerHTML = place.name+' '+' <button id="edit" type = "button" class = "btn btn-link">(edit)</button>';
// ...while the listener uses jquery to select the
// element. On clicking, I toggle.
$('#mything').on('click', function() {
$('#stuff2').toggle();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mything">
</div>
<div id="stuff2">
<p>Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt.</p>
<p>Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Vivamus suscipit tortor eget felis porttitor volutpat. Nulla porttitor accumsan tincidunt. Vivamus suscipit tortor eget felis porttitor volutpat.</p>
</div>
Upvotes: 1