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");
});
Related
I have an input-text. If you type something, the text appears below (see code snippet).
Now, I need to do the same with a previous step: clicking a button (preferably a checkbox) to append/remove all. Here is my failed idea: DEMO (it appends the input text, but when you type, text won't apear below like it does on my code snippet).
I feel like the function to add text below does not work because there is a problem with selecting the appended element. How do I do this?
Any more simple idea to do this would be great
var name1 = document.getElementById('name');
name1.addEventListener('input', function() {
var result = document.querySelector('.X');
console.log(this.value );
result.innerHTML = this.value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>What is your name? </label><input type="text" id="name">
<p>Your name is: <span class="X"></span></p>
Put your first part of the snippet into appending logic while clicking the add button. As in your codes, the input box is appended to the document after its listener being attached.
if (!added) {
$content = $(NewContent).appendTo('.firstappend');
// attach listener after input box actually exists!
var name1 = document.getElementById('A');
name1.addEventListener('input', function() {
var result = document.querySelector('span.Y');
console.log(this.value );
result.innerHTML = this.value;
});
}
$(function() {
let NewContent = '<div class="added">' +
'<p>' +
'<label>What is your name? </label>' +
'<input type="text" id="A">' +
'</p>' +
'<p>Your name is: <span class="Y"></span></p>' +
'</div>';
$(".addremove").on('click', function() {
if ($(".added").length) {
$(".added").remove();
} else {
$(".firstappend").append(NewContent);
}
});
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toadd">
<button type="button" class="addremove">Do you have a name?</button>
</div>
<div class="firstappend"></div>
as from the DEMO you included,
appended elements to document cannot be invoked explicitly, since you're using jQuery, you can do this
$(document).on('change keyup', '#A', function(event) {
$("span.Y").html($(event.currentTarget).val());
});
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/
I have a dynamic table that I will be submitted to database.
The html is looked like this :
<form id="upload">
<div class="box-body">
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="tableReport">
<thead>
<th>TYPE</th>
<th>ITEM</th>
<th>DAMAGE</th>
<th>REPAIR</th>
<th>REMARKS</th>
<th>MANHOUR</th>
<th><button class="btn btn-block btn-primary" id="addRow" type="button">ADD</button></th>
</thead>
<tbody>
<!--GENERATED BY JQUERY-->
</tbody>
</table>
</div>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-info" type="submit">Upload</button>
</div>
</form>
See, on my <th>, I have a button with id addRow that have a function to add a row on a last row.
This is the code :
$(document).on('click', '#addRow', function () {
var selType = '<select class="form-control" name="type">';
var selItem = '<select class="form-control" name="item">';
var selDamage = '<select class="form-control" name="damage">';
var selRepair = '<select class="form-control" name="repair">';
$.each(<?php echo json_encode($type); ?>, function (i, elem) {
selType += '<option>' + elem.NAMA_TYPE + '</option>';
});
$.each(<?php echo json_encode($item); ?>, function (i, elem) {
selItem += '<option>' + elem.NAMA_ITEM + '</option>';
});
$.each(<?php echo json_encode($damage_codes); ?>, function (i, elem) {
selDamage += '<option>' + elem.NAMA_DAMAGE + '</option>';
});
$.each(<?php echo json_encode($repair_codes); ?>, function (i, elem) {
selRepair += '<option>' + elem.NAMA_REPAIR + '</option>';
});
selType += '</select>';
selItem += '</select>';
selDamage += '</select>';
selRepair += '</select>';
$("#tableReport").find('tbody').append('<tr><td>' + selType +
'</td><td>' + selItem +
'</td><td>' + selDamage +
'</td><td>' + selRepair +
'</td><td><input type="text" class="form-control name="remarks" placeholder="Describe it..">' +
'</td><td><input type="text" class="form-control time" name="manhour">' +
'</td><td><button class="btn btn-block btn-danger">Delete</button>' +
'</td></tr>');
$(".time").inputmask("hh:mm");
});
Now, this is the problem. How to handling the form. When <button class="btn btn-info" type="submit">Upload</button> is clicked to submit, I will handled it use jquery ajax. The code looked like this
$(document).on('submit', '#upload', function(){
/*First, How to handled the dynamic row ?? */
/* Commonly, I use var aVar = $('selector').val(); */
/* Ex, I have two rows, How bout to handle two select option in different row ?*/
$.ajax({
url: 'LINK TO CHECK THE POST if has SUBMITTED',
type: 'POST',
data : {/*dynamic row that will be passed : data*/}
dataType: 'json',
success: function(obj) {
})
return false;
});
How can I handle that dynamic row, and how can I debug if the post have success ?
UPDATED
This code to check the condition of a ship container. If a container have many damage, it will be representated with one row as one damage. If the container have 3 damage, it will be have 3 rows. I want to submit it on a table in my database in tbl_damage_detail. I have plan to multiple insert. So, I Imagine to store that rows into an array. with foreach, I will be inserted them.
JSFIDDLE
If the inputs are added correctly to the form you just need to submit the form with AJAX, no need for anything special, one way is to use the jQuery serialize() method like this.
$(document).on('submit', '#upload', function(event){
$.ajax({
url: 'LINK TO CHECK THE POST if has SUBMITTED',
type: 'POST',
data : $(this).serialize(),
dataType: 'json',
success: function(obj) {
})
event.preventDefault();
});
with your code,i really don't know what you want to do .
first, "on" is used to bind event with dynamic dom ,but id=addRow is not a dynamic dom,it is unnecessary to use on
"$(document).on('click', '#addRow', function () {"
just use $("#addRow").click( function () {...})
and then, <form id="upload">, i am not sure you have decide to post date to service with submit, in fact ,here is a dynamic table ,if you use submit to post your data ,it may complex with your whole table data .(using submit , input must set the name tag)
i suggest you should handle each row data
//get every row data
var tableData = [] ;
$("#tableReport tbody tr").each( function(){
var tr = &(this);
var text2 = tr.find(".time").val(); //should use more clean tag
var data = {test2:test2}//...
tableData.push(data)
//use ajax with the data
});
//next handle the tableData with ajax
this scene is very fat to mvvm like: angular , vue.js or avalon.js ,use one of them,with more clean but less code .
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 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");
});