creating dynamic button and events in jquery - javascript

how to create a dynamic button with respect to XML data.Here i have to convert the name (XYZ) to a button and making an event to each dynamic button.Now am getting xyz,50 but i want to change it as button with name xyz,and also events.
<class_members>
<student>
<name>XYZ</name>
<marks>50</marks>
</student>
<student>
<name>ABC</name>
<marks>25</marks>
</student>
</class_members>
jquery code is here.
<script>
$(document).ready(function () {
$("#Submit").click(function () {
$.ajax({
type: "GET",
url: "marks.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('student').each(function () {
var Name = $(this).find('name').text();
var Mark = $(this).find('marks').text();
$("#content").append('<li>' + Name + " ," + Mark + '<li>');
});
}
});
});
});
</script>
</head>
<body>
<form id="From1" method="post">
<input type="button" value="submit" name="Submit" id="Submit" />
<div id="content">
</div>
</form>

add button with some class and attach event using that class, like, change:
$("#content").append('<li>' + Name + " ," + Mark + '<li>');
to
$("#content").append("<li><input type='button' class='dyna_btn' value='"+Name+"' /></li>");
and attach event to these buttons:
$(document).on("click", ".dyna_btn", function() {
//do something here
console.log("button clicked");
});

Related

jquery function on button click from ajax request

So im building this page where i am including a file input using ajax, but i am not able to trigger jquery when a the file is changed. is this a normal thing or should this just work? I am trying to get the filename displayed in the input type text field.
My ajax call
$('.wijzigproduct').on('click', function () {
var productvalue = $(this).val();
$.ajax({
url: "includes/productwijzigen.php?q=" + productvalue,
success: function (result) {
$('#editproduct').html(result);
}
});
});
My input fields:
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Bladeren… <input type="file" name="imgInpnew" id="imgInpnew">
</span>
</span>
<input type="text" class="form-control" id='imgOutpnew' readonly>
</div>
<img id='imgshownew'/>
My jquery:
$('#imgInpnew').change(function () {
var filename = $('#imgInpnew').val();
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length);
$('#imgOutpnew').val(filename);
});
The change() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future.
Since you have generated DOM using jQuery, you have to create a "delegated" binding by using on() . Here is the solution base on the code you have provide on jsfiddle.net/a70svxto
$.ajax({
url: "/echo/js/?js=<div class=\"input-group\"><span class=\"input-group-btn\"><span class=\"btn btn-default btn-file\">search… <input type=\"file\" name=\"imgInpnew\" id=\"imgInpnew\"></span></span><input type=\"text\" class=\"form-control\" id='imgOutpnew' readonly></div><img id='imgshownew\'/>",
success: function(result) {
$('#div').html(result);
}
});
$('#div').on('change', '#imgInpnew', function() {
var filename = $('#imgInpnew').val();
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length);
$('#imgOutpnew').val(filename);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'></div>
well you are attaching the change event to a not existing element in the DOM.
you have to first add the element into the DOM and then attach the event to the element
$.ajax({
url: "/echo/js/?js=<div class=\"input-group\"><span class=\"input-group-btn\"><span class=\"btn btn-default btn-file\">search… <input type=\"file\" name=\"imgInpnew\" id=\"imgInpnew\"></span></span><input type=\"text\" class=\"form-control\" id='imgOutpnew' readonly></div><img id='imgshownew\'/>",
success: function(result) {
$('#div').html(result);
$('#imgInpnew').change(function() {
var filename = $('#imgInpnew').val();
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length);
$('#imgOutpnew').val(filename);
});
}
});
https://jsfiddle.net/a70svxto/

JQuery Dynamic Button

I have a input box. I enter the search term and the values get returned. What I am trying to do is click the dynamic button with the value attached to it. However when I click on the button it reloads the page instead of showing an alert box. This only happens with the dynamic button not the searchButton
$(document).ready(function () {
$('.cta-button').click(function () {
event.preventDefault();
alert("You clicked the button");
});
$('#searchButton').click(function () {
event.preventDefault();
var varSearch = $('#searchDB').val();
if (!varSearch) {
$('#result').html("Please enter a search term");
return;
}
$.ajax({
contentType: "application/json; charset=utf-8",
data: 'ID=' + varSearch,
url: "getTest.ashx",
dataType: "json",
success: function (data) {
var result = '';
$.each(data, function (index, value) {
result += '' +
'<div class="main-area bg-white">' +
'<div class="row">' +
'<div class="medium-6 columns">' +
'<button type="submit" id="OfferID_' + index + '" class="cta-button cta-button-icon">Add to Cart</button>' +
'<br />' +
'</div>' +
'</div>' +
'</div>'
});
if (!result) {
result = 'No data were found for ' + varSearch;
};
$('#result').html(result);
}
});
});
});
<section>
<div class="row">
<div class="medium-4 columns medium-centered">
<div class="search-rewards">
<input type="search" id="searchDB" />
<button type="submit" id="button" class="button"></button>
</div>
</div>
</div>
<div class="row">
<div class="medium-6 columns medium-centered">
<div id="result">
</div>
</div>
</div>
</section>
You're missing the event argument to your click functions. Without it, event.preventDefault() does nothing.
$('.cta-button').click(function(event) {
event.preventDefault();
alert("You clicked the button");
});
Update
To bind to dynamic buttons, you'd need to use a delegate as #MACMAN suggested:
$(document).on('click', '.cta-button', null, function(event){
event.preventDefault();
alert("You clicked the button");
});
Use delegate to assign the click property to the dynamic button.
Sometimes JQuery events not working for dynamically generated elements. You can use JQuery.on() for dynamically generated elements.
http://api.jquery.com/on/
try using this
$('.cta-button').on("click", (function() {
event.preventDefault();
alert("You clicked the button");
});

Pass ID of button to a form

I found this pass id to jquery modal form but seeing as I'm not too jQuery-savvy and I don't know PhP I'm not sure how I would implement this in my example.
My goal is to be able to pass the ID of a button, upon being pressed, to a form. Something like this:
<button id="dynamic_id">
<form id="time_form" action="{% url 'event' pk='button_id' %}" method="post">
# Lots of stuff
</form>
The button_id is where I'd like the button's ID to be.
I thought of something like
function getId(button_id) {
document.getElementById('time_form').action = "{" + "%" + "url " + "event" + ' pk="' + button_id + '" %" + "}"';
}
<button id="dynamic_id" onClick="getId(this.id);">
<form id="time_form" action=""> (...)
</form>
But this does not work. I get an error message
400 Bad Request: Your browser semt a request this server cannot understand
UPDATE
I'm not trying this:
function getId(button_id) {
var vk_input = document.CreateElement("input");
vk_input.name = "vk_id";
vk_input.value = button_id;
vk_input.type = "hidden";
document.getElementById("time_form").appendChild(vk_input);
}
But it does not work for some reason. What's wrong with it?
look this:
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var id=$(this).attr('id');
var array_ids = [];
$('.dinamics').each(function(){
//console.log('gdfg');
array_ids.push($(this).attr('id'));
});
for(var i = 0; i < array_ids.length; i++){
$('#time_form').append('<input type="hidden" name="your_button_id_'+i+'" value="'+array_ids[i]+'"/>')
}
$('#time_form').submit();
})
})
</script>
How aboout this with jquery.
<button id="dynamic_id">
<form id="time_form" action="" method="post">
</form>
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var id=$(this).attr('id');
$('#time_form').append('<input type="hidden" name="your_button_id" value="'+id+'"/>')
$('#time_form').submit();
})
})
</script>
Button id passed correctly to getId() but generated string does not seems valid, here is some issue with quotes. See reduced example on jsfiddle
try this:
document.getElementById('time_form').action = "{" + "%" + "url " + "event" + ' pk="' + button_id + '" ' + "%" + "}";
i recommend you to use jquery, is better an clean.
this is what you want?
<button id="dynamic_id" class="dinamics">Lots of stuff</button>
<button id="dynamic_id_1" class="dinamics">1</button>
<button id="dynamic_id_2" class="dinamics">2</button>
<button id="dynamic_id_3" class="dinamics">3</button>
<button id="dynamic_id_4" class="dinamics">3</button>
<button id="dynamic_id_5" class="dinamics">3</button>
<button id="dynamic_id_6" class="dinamics">3</button>
<button id="dynamic_id_7" class="dinamics">3</button>
<form id="time_form" action="" method="post">
</form>
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var array_ids = [];
$('.dinamics').each(function(){
array_ids.push($(this).attr('id'));
});
for(var i = 0; i < array_ids.length; i++){
$('#time_form').append('<input type="hidden" name="your_button_id_'+i+'" value="'+array_ids[i]+'"/>')
}
$('#time_form').submit();
})
})
</script>

Easiest way to add a button on each row of a table HTML

I am trying to create a table in HTML that as a button on each row that acts a delete button. So when the button is click it will delete the html row as well as a row in the DB. What is the easiest way to do this?
This is what i have so far but it doesn't look good at all:
function GetSongs(id) {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetSongs", "Game")",
data: { playlistId: id },
success: function (data) {
json = data;
var obj = JSON.parse(json);
for (var i in obj) {
songCount++;
playlist.push(obj[i].SongURL);
$("#song-table").append("<tr><td>" + obj[i].SongURL + "<button class=" +"editbtn" +">edit</button>"+ "</td></tr>");
}
$('#song-count').empty();
$('#song-count').append('Song Count: ' + songCount);
}
});
}
Here is my table:
<div id="player-playlist" style="height: 300px; overflow:scroll; overflow-x: hidden">
<table class="zebra" id="song-table" style="width:400px;">
<tr>
<th>Song</th>
</tr>
</table>
</div>
You can add delete buttons the same way you're adding edit buttons:
$("#song-table").append("<tr><td>" + obj[i].SongURL + "<button class=" +"delbtn" +">delete</button>"+ "</td></tr>");
$('button.delbtn').click(function(){
$(this).parent().remove();
});
http://jsfiddle.net/qGGPZ/2/
Give your button an onclick Javascript function that includes the id as a parameter:
"<button type='button' onclick='deleteThisItem(" + id + ")' >delete</button>"
Javascript function:
function deleteThisItem(theID){
// ajax call to delete theID from database
// refresh the table
}

How do pass the id of a form onKeyUp?

There's plenty of questions on how to get the value onKeyUp, but I want to pass the id of the form onKeyUp as well.. I tried something like this, but it's telling me getId is not defined.
function getId(x){
$('.not').append(x);
}
var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='"+word+"'
name='"+word+"' onkeyup='getId("+word+")'></form> ");
http://jsfiddle.net/evs3A/
Also is putting something like "+variable+" bad practice, because I'm using it quite a lot ;)? Thank u.
Use jQuery to hook up the event and avoid the problem altogether. Try this:
var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='" + word + "'
name='" + word + "'></form> ");
$('.questions input').on('keyup', function(e) {
$('.not').append(this.id);
});
Example fiddle
you can change it into this:
$('.why').html("<form class='questions'><input type='text' id='"+word+"'
name='"+word+"'></form> ");
and in jquery:
$(document).ready(function(){
var word = 'HELP';
$(document).on('keyup', '#' + word, function(){
$('.not').append(word); //or $(this).attr('id'); if the id is the argument that you want to pass
});
});
if you want to change a variable to pass you can use data value like this:
<input type='text' id='"+word+"' name='"+word+"' data-something="new_value">
and take it in this mode:
$(document).on('keyup', '#' + word, function(){
$('.not').append(word);
var value = $(this).data('something');
});
Here's a sample without any jQuery.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
byId('myFormId').addEventListener('keyup', onFormKeyUp, false);
byId('myFormId2').addEventListener('keyup', onFormKeyUp, false);
}
// this function was attached to the form in the mInit function.
// as a consequence, 'this' reffers to the form itself.
// this.id should give us the id of the form
function onFormKeyUp(e)
{
alert("Keyup detected in the form with the id: '" + this.id + "'");
}
</script>
<style>
</style>
</head>
<body>
<form id='myFormId'>
<input id='textField1'/>
<br>
<button>Some button</button>
</form>
<form id='myFormId2'>
<input id='textField2'/>
<br>
<button>Some button</button>
</form>
</body>
</html>

Categories

Resources