Reputation: 1196
add image dynamically, but I have a problem when I input link in textbox images are not showing.
Here's a screenshot :
In FireBug I see the following error:
ReferenceError: toggle is not defined
Here is my code:
<script>
// Max Image
var maxSlide = 2000;
// Start Image
var curSlide = 0;
// Start Id dynamic
var Ids = 0;
function generateSlide() {
// If Textboxt input link image, this id="img_dynamicid" src show
function toggle(element) {
we = element.value;
document.getElementById('img_'+Ids+'').src=we;
}
if( curSlide < maxSlide ) {
var html ='<div class="row" id="slideAdd_'+Ids+'" >';
html+=' <div class="col-md-12">';
html+=' <div class="box">';
html+=' <div class="box-content">';
html+=' <form action="#" id="slide_'+Ids+'" class="form-horizontal" enctype="multipart/form-data">';
html+=' <div class="form-group">';
html+=' <div class="col-sm-9 col-lg-10 controls">';
html+='<center><img src="../images/noimage.png" id="img_'+Ids+'" style="width:150px;height:150px"></center><br/>';
html+=' </div>';
html+=' </div>';
html+=' <div class="form-group">';
html+=' <label class="col-sm-3 col-lg-2 control-label">Link Image</label>';
html+=' <div class="col-sm-9 col-lg-10 controls">';
html+=' <input type="text" onkeyup="toggle(this)" placeholder="Link Image" name="link_'+Ids+'" id="judul_'+Ids+'" class="form-control" required>';
html+=' </div>';
html+=' </div>';
html+=' <div class="form-group">';
html+=' <div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2">';
html+=' <button onClick="removeSlide(\''+Ids+'\'); return false;" class="btn btn-danger"><i class="fa fa-times"></i> Remove</button>';
html+=' </div>';
html+=' </div>';
html+=' </form>';
html+=' </div>';
html+=' </div>';
html+=' </div>';
html+=' </div>';
$("#main-content").append(html);
curSlide++;
Ids++;
$("#counter").html(curSlide+" from 2000");
}
}
</script>
<button type="submit" class="btn btn-primary" onClick="generateSlide()" ><i class="fa fa-plus"></i>Add Images</button>
<span id="counter" >0 from 2000</span>
Upvotes: 1
Views: 174
Reputation: 301
To be honest, you should attach events using jQuery. But if you want to do this way, you should put the toggle() outsite and pass the id parameter to it
function toggle(id){
document.getElementById('img_'+id+'').src = this.value;
}
function generateSlide() {
// ...
html+='<input type="text" onkeyup="toggle(' + Ids + ')" placeholder="Link Image" name="link_'+Ids+'" **id="judul_'+Ids+'"** class="form-control" required>';
// ...
}
Upvotes: 1
Reputation: 7405
You are defining the toggle function inside your function and thus it isn't accessible in global scope where the event handler is tried to be executed. Thus you need to move the toggle definition out of the scope of function generateSlide.
It should look like
function toggle(element) {
we = element.value;
document.getElementById('img_'+Ids+'').src=we;
}
function generateSlide() {
// If Textboxt input link image, this id="img_dynamicid" src show
Upvotes: 0