This html form gets displayed by a bit of javascript code. Now I want to add the information of the cells in my table, when I click on them, to this kind of alert.
How can I do that?
<div class='alertBox' id='box'>
<script type="text/javascript">
$(document).ready(function() {
$('#tableBody td').on('click', function() {
alert($(this).html() + ' ' + months[currentMonth] + ' ' + currentYear);
});
});
</script>
<form>
<input name='Event' type='text' value='Event'> <br>
</form>
<a onclick='unpop()' class='close'>Close</a>
</div>
...
This is a website, where you can add appointments to a calendar and afterwards the appointments will be displayed by a raspberry pi.
Thank you for your answer.
I already found another solution.
Here it is if you are interested:
$(document).ready(function() {
$('#tableBody td').on('click', function() {
var cellIndex = document.getElementById('displayDate').innerHTML = $(this).text() + ' ' + months[currentMonth] + ' ' + currentYear;
});
});
function pop() {
document.getElementById('box').style.display = 'block';
cellIndex;
}
function unpop() {
document.getElementById('box').style.display = 'none';
}
If the HTML for the alert box is added by javascript, then you will need to use .on() to catch user events (this is called event delegation). Also, when you do that, you must attach the .on() method to an element that definitely exists before the javascript is run - $(document) is always safe.
Try this:
$(document).ready(function() {
$(document).on('click', '#tableBody td', function() {
let txt = $(this).text();
$('#box input[name=Event]').val(txt);
$('#box').show();
});
$(document).on('click', '#box a.close', function(){
$('#box').hide();
});
});
table{border-collapse:collapse;}
th,td{border:1px solid #ccc;}
#box{position:absolute;top:5vh;left:20vw;padding:2vh;background:wheat;display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class='alertBox' id='box'>
<form>
<input name='Event' type='text' value='Event'> <br>
</form>
<a class='close'>Close</a>
</div>
<table>
<thead><th>Name</th><th>Vehicle</th></thead>
<tbody id="tableBody">
<tr><td>Bob</td><td>Car</td></tr>
<tr><td>Sam</td><td>Truck</td></tr>
<tr><td>Fred</td><td>Bike</td></tr>
</tbody></table>
Related
I tried to pass data through the click method to test it out so that I do not have to call a function from handler onclick. I want to do this to prevent the default submit whenever I press any button. Like this instead of having.
<button onclick="addAuthor()">Add Author</button>
I can have something like:
<button id="addAuthor">Add Author</button>
Which would go to.
$("#addAuthor").click({
id: 100
}, addAuthor);
Then.
function addAuthor(dataMap) {
alert(dataMap.data.id)
//add another author
}
I want the button "Remove div2" to do the same thing the span "Remove" does.
For now I had it to give an alert with the value of 100 but it does not even do that.
$("removeDiv").click({bookDiv: count}, removeDiv);
This is what I want to put so that the variables are passed but the test doesn't work.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
////////////////////////////////////////////////
//HERE
$("#removeDiv1").click({
id: 100
}, removeDiv1);
////////////////////////////////////////////////
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>'
///////////////////////////////////////////////////
////HERE
+ '<button id="removeDiv1"> Remove div2</button>'
///////////////////////////////////////////////////
+ '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
///////////////////////////////////////////
//HERE
function removeDiv1(dataMap) {
alert(dataMap.data.id)
}
///////////////////////////////////////////
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr)
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
The problem isn't with passing in the dataMap (try it without it; it still won't work).
The problem is that when you attempt to set your click handler with $("#removeDiv1").click(...), the #removeDiv1 element doesn't exist yet - it's created and added to the DOM later, in addMore.
You need to do one of the following:
Set your click handler inside of addMore, after str is appended.
Change your click handler to use jQuery's event delegation capabilities. $("#removeDiv1").click(...) becomes $("body").on('click', '#removeDiv1', ...)
Side note: the "body" selector can be replaced by any selector that will select an ancestor of #removeDiv1; the click event propagates up from #removeDiv1 to its parent, its parent parent, and so on, until it's handled and something calls e.stopPropagation(), or until it reaches the document root.
First off, this is really something that Angular or something like it can do much better.
Next, I wouldn't use ids. You can do the same thing with classes without having to increment and restrict your code. Here's how I'd code the HTML:
<div>
<h1>My favorite authors and their books</h1>
<button class="js-add">Add An Author</button>
<div class="authors"></div>
<button class="js-save">Save</button>
</div>
I've also pulled all the javascript out of the HTML.
Next, "click" won't apply to items added after it is stated. You either need to re-state a click for the new element, or you need to use "on". Note in the code below that I can use the "click" method for "add Author" because that button exists when the script was run. For the other buttons, I had to use "on('click'..."
var addAuthor = function($this) {
var books = $('<div>')
.addClass('books')
.append(
$('<button>')
.addClass('js-addBook')
.html('Add a book')
)
.append(
$('<div>')
.addClass('bookName')
.html('Books:')
);
addBook(books.find('button'));
$($this)
.parent()
.find('.authors')
.append(
$('<div>')
.addClass('author')
.append(
$('<div>')
.addClass('authorName')
.html('Author: ')
.append(
$('<div>')
.addClass('remove js-removeAuthor')
.html('x')
)
.append(
$('<input>')
)
)
.append(
books
)
)
};
var addBook = function($this) {
$($this)
.parent()
.append(
$('<div>')
.addClass('book')
.append(
$('<div>')
.addClass('remove js-removeBook')
.html('x')
)
.append(
$('<input>')
)
)
};
addAuthor($('button.addAuthor'));
$('.js-addAuthor').click(function() {
addAuthor(this);
});
$('.authors').on('click', '.js-addBook', function() {
addBook(this);
});
$('.authors').on('click', '.js-removeBook, .js-removeAuthor', function() {
$(this)
.parent()
.remove()
});
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/rt3tpeta/3/
I am doing an ajax to pull information from a spreadsheet on my google drive, and then using the following code to display them in HTML:
I have this HTML:
<section class="p-booking" id="booking">
<div class="container">
<div class="row">
<div class="event-box">
<!-- caixas puxados do drive -->
</div>
</div>
</section>
And this JS:
$.getJSON(url, function (data) {
var caixasEvento = [];
caixasEvento.push('<div class="col-md-3">');
caixasEvento.push('<div data-id="' + something + '" class="box">');
caixasEvento.push('<h1 class="day">' + something + '</h1>');
caixasEvento.push('<h1 class="local">' + something + '</h1>');
caixasEvento.push('<img class="local-img" src="' + image + '">');
caixasEvento.push('</div>');
caixasEvento.push('</div>');
$('.event-box').append(caixasEvento.join(''));
});
And then I need an alert every time someone clicks the box:
$('.box').on('click', function() {
alert('test')
});
I'm using a script link tag in the bottom of my html document.
the box is normally appearing with all the drive information.
It does not work. I believe that is a problem related to the ajax, because if I create a div with the 'box' class, the alert works.
I'm guessing this is happening because the box element doesn't exist on the page when you try to setup the listener. Try this:
$('.event-box').on('click', '.box', function() {
// do stuff here
});
Try this:
$('.box').each(function()
{
$(this).click(clickHandler);
});
function clickhandler()
{
alert('test')
}
I have a form with several rows. each row has a product column with a name starting product. so the names are product1, product2, product3 etc etc.
I have an autocomplete script as follows:
<script type="text/javascript">
$(function(){
$("#product1").autocomplete({ //product is input cell to reference. autocomplete is a jquery function that is being called.
source: "get_sku_codes",
messages: {
noResults: '',
results: function() {}
}
});
});
</script>
This works great on input product1 but does not work on product2 as the script obviously references a different input.
How can I modify my script to be triggered when any cell starting with product is populated?
UPDATE with dynamic content
<script type="text/javascript">
var counter = 1;
jQuery("table.authors-list").on('change','input[name^="qty"]',function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr>'+
' <td><a class="deleteRow"> <img src="<?php echo base_url() ?>application/assets/images/no.jpg" /></a></td>' +
' <td><input type="text" id="product' + counter + '" name="product' + counter + '" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset" /></td>'+
' </tr>');
jQuery('table.authors-list').append(newRow);
});
</script>
Dipesh update
<script type="text/javascript">
var counter = 1;
jQuery("table.authors-list").on('change','input[name^="qty"]',function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr>'+
' <td><a class="deleteRow"> <img src="<?php echo base_url() ?>application/assets/images/no.jpg" /></a></td>' +
' <td><input type="text" id="product_' + counter + '" name="product_' + counter + '" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset" /></td>' +
' </tr>');
jQuery('table.authors-list').append(newRow);
$('#product'+counter).autocomplete(
{
source: "get_sku_codes",
messages: {
noResults: '',
results: function() {}
}
});
});
jQuery("table.authors-list").on('click','.deleteRow',function(event){
if ($(this).parents('table').find('tr').length > 2) { //get number of rows(TR's) in table
$(this).closest('tr').remove();
}else{
alert ('Form must have at least one row') // alert if only one row left in table
}
});
</script>
Use attribute starts with selector [name^="value"]
Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.
$('input[name^="product"]').autocomplete({
Official Document
For Dynamic loaded
You can use .on for that.
$('input[name^="product"]').on('focus',function(){
// code for $(this).autoComplete();
});
According to updated code you can add below code so newly added DOM has autocomplete code attached.
$('#product'+counter).autocomplete(
{
source: "get_sku_codes",
messages: {
noResults: '',
results: function() {}
}
});
add above code after append statement.
try to apply a same class to all those elements
$(".className").autocomplete({
or
$("input[name^='product']").autocomplete({
What is id #product1 on? div? a tag?
Say, if it is a div, loop through all the elements:
$('[.(container wrapper) > div]').each(function () {});
where .(container wrapper) is the class name of the div or p or whatever that encloses you 'products' ..naturally, you would remove the [] ..only for demontration and for the whole thing to make sense.
try multi selector
$("input[id^='product']").autocomplete({ //if you have ID
.....
$("input[name^='product']").autocomplete({ //if you have name
.....
updated
creata a function
function callAutocomplete(obj)
{
$('#'+obj).autocomplete{
//your autocompletecode
};
}
call this function after this line
.....
jQuery('table.authors-list').append(newRow);
callAutocomplete("product" + counter);
and here
$(function(){
callAutocomplete("product1"); //remove other code that u mentioned above
});
and that should do the trick...
I have this code:
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#k123").click(function () {
//var text=$(this).val(); //this does not work
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" onclick="save();" value="save"><input type="button" onclick="cancel();" value="cancel"></div>';
$(this).replaceWith(k);
});
});
function save() {
}
function cancel() {
//alert(text);
var k='<div id="k123"></div>';
$("#k123").replaceWith(k);
}
</script>
</head>
<body>
<div id="k123">aaaaa</div>
</body>
</html>
My question is :
1)In both functions : cancel & save , How can I get content of div id->#k123->textarea->content
functions cancel & save are outside the scope and they are independent functions I cannot tell $(this).parent().
I need to ask about div which has id #k123 , then get inside to textarea's content and get it.
and I have also to get id #k123 automatically because if I have many divs I cannot tell save & cancel manually the div's id, cancel & save should know the div's id sender from the input type='button'`s parent id.
**please I do not prefer the suggestion of sending div id from input button
**We are assuming that both input buttons have no IDS or Names
I tried another way but still having same problem
I replaced
$(document).ready(function() {
$("#k123").click(function () {
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel"></div>';
$(this).replaceWith(k);
});
//$("#k123 > input").click(function() {
$("#k123").children("input:second").click(function() {
alert("hi");
});
});
thank you.
I have the working code for you below. You don't even need an id.. just a container div and delegation of events. The below accomplishes what I thought you were after, in what I believe to be a much simpler, and much more efficient fashion:
(I've added comments to assist in understanding the code)
$(document).ready(function() {
$(".container").on('click', function(e) {
if (!$(e.target).is('input') && !$(e.target).is('textarea')) { //check to make sure the target is neither an input or a textarea
var div_text = $(e.target).text(); // use a variable named something other than text, because text is already a method for another element
$(e.target).data('text',div_text); // set the div's current contents as a hidden data attribute, to be retrieved later. You can get rid of this and the other line if you want cancel to completely wipe the div.
var k = '<textarea rows="10" cols="10">' + div_text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel">';
$(e.target).html(k); //set the inner HTML of the div, so we don't lose any data saved to that div
}
if ($(e.target).is('input') && $(e.target).val() == 'save') {
$(e.target).parent().html($(e.target).parent().find('textarea').val()); // replace the current contents of the parent div with the contents of the textarea within it.
} else if ($(e.target).is('input') && $(e.target).val() == 'cancel') {
$(e.target).parent().html($(e.target).parent().data('text')); //set the contents to the old contents, as stored in the data attribute. Just replace the contents of the .html() here with '' to completely clear it.
}
});
});
DEMO
REVISED - WORKS
Check this out... not quite there but close!
REVISED JS Fiddle
function editit() {
var divId = $(this).attr('id');
var text = $(this).html();
var k = '<div id="' + divId + '" class="editable"><textarea id="newvalue' + divId +'" rows="10" cols="10">' + text + '</textarea><br /><input id="save' + divId + '" type="button" value="save"><input id="cancel' + divId + '" type="button" value="cancel"></div>';
$('#' + divId).replaceWith(k);
$('#cancel' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + text + '</div>');
$('.editable').bind('click', editit);
});
$('#save' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + $("#newvalue" + divId).val()+ '</div>');
$('.editable').bind('click', editit);
});
}
$('.editable').bind('click', editit);
<script type="text/javascript">
$("a.route").live('click', function() { // live is better
$("#results").load( $(this).attr('href') );
return false;
});
</script>
That's the code, how can I incorporate the code you just gave me?
The Confirm dialog returns true if the user clicks the OK button, or false if the user clicks on the Cancel button. You can use this value to trigger your script if they've clicked OK like this:
<script type="text/javascript">
$("a.route").live('click', function() {
if (confirm("Are you sure?")) {
$("#results").load( $(this).attr('href') );
}
return false;
});
</script>
if you want to use a custom box you could do it like that:
test link: http://jsfiddle.net/myDry/
function blockmeornot(extlink) {
var oherf = $(extlink).attr('href')
var msgboxID = 'areyousure'
var msgbox = '<div id="' + msgboxID +'"><div><p> put your message here </p><a class="yes" href="' + oherf + '"> yes </a> <a class="no" href="#"> no </a></div></div>'
$('body').append(msgbox)
$('#' + msgboxID + ' a.no').live('click', function(){ $('#' + msgboxID).fadeOut(400, function(){$(this).remove()}) })
}
$('a.external').click(function(){ blockmeornot(this); return false })