Reputation: 29
I have a php page that includes 5 php files. in each of the files, I put an input[button] for each php file, when the user click on it, the function will be fired. As I'm not allowed to use same ID in the page, I'm getting confused to apply $(document).ready(function(){..}) for each ID. How can I handle it? More clearly: I have ('#add_more1,#add_more2,#add_more3,#add_more4,#add_more5). What I want is when the user click on each of those ID's, it fires the code below. for example if he click on ('#add_more2') , it will run the code thank's in advanced.
// To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
$('#add_more2').click(function() {
$('#show2').append($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append($("<input/>", {
name: 'file[]',
type: 'file',
id: 'file'
})));
});
// Following function will executes on change event of file input to select different file.
$('body').on('change', '#file', function() {
if (this.files && this.files[0]) {
counter += 1; // Incrementing global variable by 1.
$(this).before("<div id='abcd" + counter + "' class='abcd'><img id='previewimg" + counter + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + counter).append($("<i/>", {
id: 'img',
top:0,
class: 'fa fa-times',
alt: 'delete'
}).click(function() {
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e) {
$('#previewimg' + counter).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name) {
alert("First Image Must Be Selected");
e.preventDefault();
}
});
Upvotes: 0
Views: 37
Reputation: 78
my suggestion if is that you used a same class for each button instead of id
$("body").on("click",".parentClass .currentClass",function() {
$("#show2").append($("<div/>", {
id: "filediv"
}).fadeIn("slow").append($("<input/>", {
name: "file[]",
type: "file",
id: "file"
}));
});
Upvotes: 1
Reputation: 1
You can use attribute begins with selector, String.prototype.replace()
with RegExp
/\D/g
to replace part of id
that is not a digit, retrieve number portion of element id
to select corresponding element having id
beginning with #show
.
$("[id^=add_more]").click(function() {
$("#show" + this.id.replace(/\D/g, "")).append($("<div/>", {
id: "filediv"
}).fadeIn("slow").append($("<input/>", {
name: "file[]",
type: "file",
id: "file"
})));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="add_more1">
add_more1
</div>
<div id="add_more2">
add_more2
</div>
<div id="add_more3">
add_more3
</div>
<div id="add_more4">
add_more4
</div>
<div id="add_more5">
add_more5
</div>
<div id="show1">
show1
</div>
<div id="show2">
show2
</div>
<div id="show3">
show3
</div>
<div id="show4">
show4
</div>
<div id="show5">
show5
</div>
Upvotes: 1