Confirm box when link is clicked - javascript

<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 })

Related

How can I add jQuery information to a html form?

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>

click(dataMap, method) version of the jQuery is not working

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/

How to call method in Controller from View on a javascript event in RoR?

I am new to RoR. I have a view file which uses javascript. Upon clinking a button, I want to call a method in Controller. How do I do that.
JS code: (folder_view.js)
function iterate(data){
var folder_names = "";
$.each(data.Folder, function(key, val) {
folder_names = folder_names + "<ul> <li id= '" + val.folder_name + "'>
<a class='a' href='' onclick='updateDiv(val.folder_name)'>" + val.folder_name +
"</a></li></ul>";
});
var divid = "folder";
var view_var2 = jQuery("<div class='scrollbar ' id='divscroll' > <div class='content ' id = " + divid + "> <ul> <li> Folder " + folder_names + "</li></ul></div></div>");
$('#folder_view').html(view_var2);
tree_view(divid);
}
function tree_view(divid){
$("#" + divid).jstree();
$("#" + divid).on("changed.jstree", function (e, data) {
console.log(data.selected);
});
$('button').on('click', function () {
$("#" + divid).jstree(true).select_node('child_node_1');
$("#" + divid).jstree('select_node', 'child_node_1');
$.jstree.reference("#" + divid).select_node('child_node_1');
});
}
Here, I am calling the UpdateDiv method upon clinking on folder. This method is available in view file which is as follows:
Folder_view.html.erb:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<script type="text/javascript" src="/assets/folder_view.js"></script>
<script type="text/javascript" src="/assets/jstree.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON('/assets/temp.json', function(data) {
iterate(data);
});
});
function updateDiv(data){
//Call a function to controller
}
</script>
<body class="bonita-body" ieonload="">
<div id="bonita_process_label" class="bonita_process_label"><div class="gwt-HTML">Console</div></div>
<div id="bonita-banneralthaut"></div>
<div id="bonita-banneraltbas"></div>
<div style='margin-top: 40px;'> <div id='folder_view'></div>
</body>
The method updateDiv is being called upon clicking a folder_name. I want fetch some folder-specific meta-data from controller for the same. How do I call any method from view to controller upon clinking?
Any references??
You need to make an AJAX call using either native XHR:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
OR by using jQuery AJAX:
https://api.jquery.com/jQuery.ajax/

How to get the attribute value of "id" from the anchor tag by class name when its clicked?

$("#jqxTree-ReportGroups ul").append("<li id=" + [data[i].Id] + " item-checked='true' item-expanded='true' class='treeLi'>
<a class='report-tree-expand' href=''>+</a>
<a class='reportData' id='12345' href=''>" + [data[i].Name] + "</a></li>");
How to get the attribute value of "id" by class name "reportData" when its clicked?
EDIT:
click doesnt work.. If i use Live that function is getting called... How to do get the reportData's Id inside a live function
Take a look at this Code:
$(document).on('click' , '.reportData' , function(){
var idProp= $(this).prop('id'); // or attr()
var idAttr = $(this).attr('id');
console.log('using prop = ' + idProp + ' , using attr = ' + idAttr);
console.log();
return false; // to prevent the default action of the link also prevents bubbling
});
done use live it has been deprecated (on requires jquery version 1.7 and above)
but here is the code using live()
$('.reportData').live('click' , function(){
var idProp= $(this).prop('id'); // or attr()
var idAttr = $(this).attr('id');
console.log('using prop = ' + idProp + ' , using attr = ' + idAttr);
console.log();
return false; // to prevent the default action of the link also prevents bubbling
});
jsfiddle to prove working
http://jsfiddle.net/uvgW4/1/
You can do
$(document).on("click", ".reportDatan", function() {
var id = this.id;
});
Use event delegation since it looks like your adding this dynamically.
Try this:
$('.reportDatan').click(function(){
$(this).attr('id');
});
if you are using jquery 1.9
$('.reportDatan').click(function(){
$(this).prop('id');
});
Your concatenation of HTML String inside jQuery is wrong, take a look at this Code which has live function or if you want this to be readable, you can use JavaScript Template Engine Mustache also
HTML:
<div id="jqxTree-ReportGroups">
<ul>
<li>First</li>
</ul>
</div>
jQuery:
$(document).ready(function () {
var yourLiID = 100;
var aValue = 'Report Data';
var yourLi = "<li id='" + yourLiID + "' item-checked='true' item-expanded='true' class='treeLi'>";
var yourAnchor = "<a class='report-tree-expand' href=''>Your Text</a> ";
var secondAnchor = "<a class='reportData' id='12345' href=''>" + aValue + "</a>";
var yourLiClose = '</li>';
$("#jqxTree-ReportGroups ul").append(yourLi + yourAnchor + secondAnchor + yourLiClose);
$('.reportData').live("click", function(){
var yourAnchorID = $(this).attr('id');
alert('yourAnchorID: ' + yourAnchorID);
return false;
});
});
Refer this jsFiddle Link for demo

Div's content editor

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);

Categories