Capturing href and prevent event default - javascript

Not sure why the code is not working. The javascript is not printing the alert box nor preventing the event default. I was under the assumption that the data would load asynchronously keeping me on the same page.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<div data-role="page">
<div data-role="header"></div>
<div data-role="content">
<p id = "heading">Is Nursing For You?</p>
<br/>
<div id = "div1" align="center"></div>
</div>
<div data-role="footer" id = "foot" data-position="fixed">
<table>
<tr>
<th><h1 id = "alignLeft">Future Goals</th></h1>
<th><h1 id = "socialMediaText alignCenter">Get Social With Us!</h1>
</th>
<th></th>
</tr>
<tr>
<td id = "alignLeft">Telephone: 304-444-39876</td>
<tr>
<td = "alignLeft">Email: futurenurseky#gmail.com</td>
</tr>
</tr>
</table>
</div>
</div>
This is where im having the trouble at. Not sure why the alert is not sending or redirecting me.
<script type='text/javascript'>
$(document).ready(function(){
$("#div1").load("FONWVhp.php");
$('#div1').click(function(e){
e.preventDefault();
alert($(this).attr('href'));
});
});
</script>
</body>
</html>
This is the Fp.php which is called when the page is loaded but once the page is loaded there are href's that are displayed. so when the person clicks the href the page will stay but the data will change and get the info coming from articles.php (at the bottom).
$sqlPAQuery = "SELECT pages.pageId, pages.pageTitle FROM pages order by
pages.pageId";
$paqueryResult = mysqli_query($conn,$sqlPAQuery);
while ($paqueryRow = mysqli_fetch_object($paqueryResult))
{
$pages = "<div class='center-wrapper'><a href = articles.php?
pageId=".$paqueryRow->pageId."><button class= center-wrapper'>".$paqueryRow-
>pageTitle."</button></a><br/><br/></div>";
echo $pages;
}
articles.php
$sqlARTICLEQuery = "SELECT * FROM articles where pageId=".$_GET['pageId']."
order by articleId";
$articlequeryResult = mysqli_query($conn,$sqlARTICLEQuery);
while ($articlequeryRow = mysqli_fetch_object($articlequeryResult))
{
$articles ="<div id = 'div1' class='center-wrapper'><a href =
article.php?articleId=".$articlequeryRow->articleId."><button id
='wrapper'>".$articlequeryRow->articleTitle."</button></a><br/><br/></div>";
echo $articles;
}

You need to wait for the div contents to load before manipulating it. Try this:
$(document).ready(function() {
$("#div1").load('FONWVhp.php', function() {
$('#div1 div.center-wrapper a button').click(function(event){
event.preventDefault();
alert($(this).parent().attr('href'));
});
});
});
Also, I've corrected some mistakes in your code:
Instead of $('#div1').click(...) use $('#div1 div.center-wrapper a button').click(...).
I suppose you want the anchor's href, so you need to use alert($(this).parent().attr('href')).

just put an e / event in the function
<script type='text/javascript'>
$(document).ready(function(){
$("#div1").load("Fp.php");
$('div.div1 a button').click(function(e){
e.preventDefault();
alert($(this).attr('href'));
});
});
</script>

Related

addEventlistener for buttons does not work properly with more than one button

I want to create a script where I can upload files via event listener drop.
Everytime a file is dropped, a new table row has to be created with a save/edit button. These buttons need event listeners for click, but the problem is that the event listener works only on the last button added to the table.
I have made a simplified example of my problem. The function clickEventSaveButton() contains an .addEventlistener, with an anonymous function. For now it just executes a console log, but only for the button in the last table row. Everytime a new button is created, the old one stops working.
JS:
'use strict';
const dragArea = document.getElementById('dragArea');
const fileTable = document.getElementById('fileTable');
const fileTableBody = fileTable.querySelector('tbody');
let id = 0;
dragArea.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
});
dragArea.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
// Add table row
fileTableBody.innerHTML += createFileTableRow(id, 'placeholder');
clickEventSaveButton(id);
id++;
});
function clickEventSaveButton(id) {
let saveButton = document.querySelector('.file-save a[data-id="'+id+'"]');
console.log(saveButton);
console.log(id);
saveButton.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
console.log('Save Button (ID:'+id+') pressed!');
});
}
function createFileTableRow(id, name) {
return `
<tr data-id="${id}">
<td class="file-name">${name}</td>
<td class="file-save">
<a data-id="${id}" class="button is-info is-small">Save</a>
</td>
</tr>
`;
};
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="script-src 'self';">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.1/css/bulma.min.css">
<script defer src="test.js"></script>
</head>
<body>
<div class="columns"><div class="column is-half is-offset-one-quarter">
<h1>Work in progress</h1>
<div id="dragArea" class="box has-background-info-light has-text-centered py-6">
Drag .xlsx files here!
</div>
<hr>
<h3 id="fileTableTitle">No files loaded...</h3>
<table id="fileTable" class="table table is-fullwidth is-hoverable">
<thead><tr><th>File</th><th>Save File</th></tr></thead>
<tbody></tbody>
</table>
<hr>
</div></div>
</body>
</html>
So, thanks to Patrick Evans I was able to solve the issue that bugged me for some hours.
Instead of innerHTML I have to use insertAdjacentHTML.
Solution:
fileTableBody.insertAdjacentHTML('beforeend', createFileTableRow(id, 'placeholder'));

capturing url and loading that urls contents into the same or different div

Wanted to know if it is possible and if so where am i failing on capturing a url and displaying the contents of that file into a div on the same page.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type='text/javascript'
src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'>
</script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<div data-role="page">
<div data-role="header"></div>
<div data-role="content">
<p id = "heading">Is Nursing For You?</p>
<br/>
<div id = "div1" align="center"></div>
</div>
<div data-role="footer" id = "foot" data-position="fixed">
</div>
</div>
$(document).ready(function() {
$("#div1").load('FONWVhp.php', function() {
$('#div1 div.center-wrapper a button').click(function(event){
event.preventDefault();
($(this).parent().attr('href'));
$("#div1").load(($(this).parent().attr('href'))'articles.php',
function() {
});
});
});
});
</script>
</body>
</html>
fonwvhp.php
index.html loads pages hrefs(which are pointed to articles.php?pageId...)once the page is clicked i want the href to load into the div1 tag and display the href results.
$sqlPAQuery = "SELECT pages.pageId, pages.pageTitle FROM pages order by
pages.pageId";
$paqueryResult = mysqli_query($conn,$sqlPAQuery);
while ($paqueryRow = mysqli_fetch_object($paqueryResult))
{
$pages = "<div class='center-wrapper'><a href = articles.php?
pageId=".$paqueryRow->pageId."><button class= center-
wrapper'>".$paqueryRow-
>pageTitle."</button></a><br/><br/></div>";
echo $pages;
}
articles.php
this is the page i would like to be placed in div1 tag after page href is clicked
$sqlARTICLEQuery = "SELECT * FROM articles where pageId=".$_GET['pageId']."
order by articleId";
$articlequeryResult = mysqli_query($conn,$sqlARTICLEQuery);
while ($articlequeryRow = mysqli_fetch_object($articlequeryResult))
{
$articles ="<div id = 'div1' class='center-wrapper'><a href = article.php?
articleId=".$articlequeryRow->articleId."><button id
='wrapper'>".$articlequeryRow->articleTitle."</button></a><br/><br/></div>";
echo $articles;
}
This is a guess but most likely you forgot the / or you have the ) in the wrong spot
Change
$("#div1").load(($(this).parent().attr('href'))'articles.php'
To
$("#div1").load(($(this).parent().attr('href')+'/articles.php')
These 2 lines
($(this).parent().attr('href'));
$("#div1").load(($(this).parent().attr('href'))'articles.php',
The first line is useless. Delete it.
The second line. You're getting the href of the parent element to the button that was clicked in content loaded from FONWVhp.php (which you didn't post, by the way so I have to guess what it is). To that you are trying but failing to append 'articles.php'.
// Delete me ($(this).parent().attr('href'));
$("#div1").load($(this).parent().attr('href') + 'articles.php',
Note that this will work fine as long as the href always ends in a slash. If it doesn't, which might be likely (depending again on what the mysterious FONWVhp.php contains) then you will have to figure that out too (by putting a slash in, most likely).

jQuery .insertAfter() copying input field values

I have created a html webpage here:
http://diagrams.inse1d.info/wbt.html
Code:
<!DOCTYPE html>
<html>
<head>
<title>WBT Charts</title>
<link rel="stylesheet" type="text/css" href="wbt.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="wbt.js"></script>
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,500,700' rel='stylesheet' type='text/css'>
</head>
<body>
<section>
<article>
<div id="wbtBlock">
<p>Press enter to save amendments</p>
<h1>Title of wbt:<input type="text" id="wbtTitle" /></h1>
<div id="graph">
<p>Graph to go here</p>
</div>
<p><strong>Notes: </strong></p>
<p><span><input type="textarea" id="wbtNote" /></span></p>
</div>
</article>
</section>
<button>Add New WBT Chart</button>
</body>
Here is the jQuery code I wrote:
$(document).ready(function() {
$("h1").keypress(function(e) {
//get
wbtTitle = $('#wbtTitle').val();
// Write text after enter
if (e.which == 13) {
$("h1").text(wbtTitle);
}
});
$("span").keypress(function(e) {
//get
wbtNote = $('#wbtNote').val();
// Write note after enter
if (e.which == 13) {
$("span").text(wbtNote);
}
});
//Insert new WBT on button click
$("button").each(function() {
$(this).click(function() {
var wbtSet = $( "article" ).html();
$(wbtSet).insertAfter('section');
});
});
});
What I want to do is set the title and some note text using input boxes which works using jQuery. I then want to add a copy of the html into another article when the button is pressed without copying the inputs previously made with the possibility of setting new values when the article is cloned. The process should repeat over and over again.
Here is an image to help explain:
I am quite new to jQuery, I think you need to use a loop to fix this, I read that a .each() can be used http://api.jquery.com/jQuery.each/ but not quite sure.
Any help will be appreciated. Thanks.
I think I got your answer.
I changed the html a bit, because you duplicated some id's with your approach, that's not good. id's have to be unique on a page. I simply changed them to classes.
<!DOCTYPE html>
<html>
<head>
<title>WBT Charts</title>
<link rel="stylesheet" type="text/css" href="wbt.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="wbt.js"></script>
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,500,700' rel='stylesheet' type='text/css'>
</head>
<body>
<section>
<article>
<div class="wbtBlock">
<p>Press enter to save amendments</p>
<h1>Title of wbt:<input type="text" class="wbtTitle" /></h1>
<div class="graph">
<p>Graph to go here</p>
</div>
<p><strong>Notes: </strong></p>
<p><span><input type="textarea" class="wbtNote" /></span></p>
</div>
</article>
</section>
<button>Add New WBT Chart</button>
</body>
And of course the jQuery. I got rid of your first two functions because they had no purpose in this context.
$(document).ready(function() {
//Insert new WBT on button click
$("button").on('click', function() {
var title = $(this).prev().find('.wbtTitle').val();
var note = $(this).prev().find('.wbtNote').val();
var wbtSet = $(this).prev("section").html();
$(this).prev().find('.wbtTitle').replaceWith(title);
$(this).prev().find('.wbtNote').replaceWith(note);
$(this).prev("section").after('<section>' + wbtSet + '</section>');
});
});
Here is a working fiddel
Fixing the answer given by hitokun_s
window.onload = function() {
// Save a copy of the element wbtSet element on pageload
var wbtSet = $("article").clone();
$("button").each(function() {
$(this).click(function() {
// Append a new one to the holder of the wbSets
$(wbtSet).appendTo($('section'));
});
});
}
I think this is what you want to do.
window.onload = function() {
$("button").each(function() {
$(this).click(function() {
var wbtSet = $("article:first-child").clone();
wbtSet.find("input").val("");
$(wbtSet).appendTo($('section'));
});
});
}

Changing element text isn't working

It always seems to be a problem and I fail to see why, I'm trying to change element p text by using his ID, element p id="para1" is inside PostEditor.html:
The elementID I want to change is para1 in the following html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
The following function is issued by a click on a link inside index.html and displaying the page you are seeing above and is then supposed to change its content:
From index.html I issue the function from link:
<a onclick="postEditing()"> Edit</a>
This line issue the following function:
function postEditing()
{
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.document.getElementById("para1").innerHTML = "11111111111";
result.document.getElementById("para1").innerText = "11111111111";
result.document.getElementById("para1").value = "11111111111";
}
As you can see I tried three methods. I'd never understand what is the difference between them, but I tried all three and none worked!
It's because you're searching the document of the window which shows the index.html, not the document of the newly opened window. try following:
...
var editorWindow = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
editorWindow.document.getElementById("para1").innerHTML = "11111111111";
...
EDIT:
NOW i see the problem: in the function you're trying to access a property of the parameter element, but you don't pass a value for it. So this will end in an error because the accessed object is undefinded!
So you have three options to get it working:
test the parameter (always a good idea): var ID = null; if(element) ID = element.id;
pass a value: <a onclick="postEditing(this)"> Edit</a>
remove the line var ID = element.id;
SOLUTION: (TESTED)
I could not really say why, but the index.html found the para1 and can successfully set the new text. But somehow the new window will reinitialize the old value again.
So you have to do the changing in an handler you run at onLoad:
index.html:
<html>
<head>
<script>
function postEditing() {
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.onload = function() {
result.document.getElementById("para1").innerHTML = "11111111111";
}
}
</script>
</head>
<body>
<a onclick="postEditing()"> Edit</a>
</body>
</html>
PostEditor.html:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<link href="styles/editor.css" rel="stylesheet" type="text/css" media="screen" />
<script src="scripts/mainScript.js"> </script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="submit" onclick="urlLoader('caller','posthandler.php')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>
I'm fairly sure you will need to query the return result of calling window.open like this:
function postEditing(element)
{
var ID = element.id;
var result = window.open('PostEditor.html', 'newwindow', 'width=350,' + 'height=350');
result.getElementById("para1").innerHTML = "11111111111";
result.getElementById("para1").innerText = "11111111111";
result.getElementById("para1").value = "11111111111";
}
[Untested though]
Your button type is submit, which is posting the form. The object is changing in the DOM, only after the script runs, the DOM is reloaded back to it's original state. Try changing your button type to "button", and you should see the P element change appropriately.
Edit: Here's the HTML I used to determine the above. Keeping the button as "submit" caused me to see the text change and then swap back. The HTML below should keep the text in place. HTH!
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<script>
function postEditing(element)
{
document.getElementById('para1').innerHTML = "asdafs";
}
</script>
</head>
<body>
<!-- Input fields -->
<div class="center">
<form id=caller method="post">
<p id="para1" class="text"><Strong>Post your message</Strong></p>
<textarea id="textEditor" rows="16" cols="34" name="content"></textarea>
<input type="button" onclick="postEditing('caller')" value="Post">
</form>
</div>
<!-- end Input fields -->
</body>
</html>

JavaScript function and DOM

I write function for manipulation with DOM objects. This function must find element with specific ID and add new child element to element with specific ID:
<html>
<head>
<title> Text </title>
<meta charset="utf-8">
</head>
<body id="tbody">
<script>
function add(){
el = document.getElementById("testform");
var nf=document.createElement("input");
nf.type="text";
el.appendChild(nf);
}
</script>
<p>
<form id="testform">
<button onclick="add();"> create</button>
</form>
</p>
</body>
</html>
Element of text input doesn't create on page,but same code is placed in script tag without function-work
You're reloading the page, and need to return false when clicking the button to stop the form from being submitted :
<html>
<head>
<title> Text </title>
<meta charset="utf-8">
</head>
<body id="tbody">
<script type="text/javascript">
function add(){
el = document.getElementById("testform");
var nf=document.createElement("input");
nf.type="text";
el.appendChild(nf);
}
</script>
<p>
<form id="testform">
<button onclick="add();return false;"> create</button>
</form>
</p>
</body>
</html>​
Also, sticking a form inside a paragraph seems unnecessary ?
FIDDLE
Since the Default action of button element type is submit so it submits every time you click. You can do a return false or create a label tag instead of button something like:
<html>
<head>
<title> Text </title>
<meta charset="utf-8">
</head>
<body id="tbody">
<script>
function add(){
el = document.getElementById("testform");
var nf=document.createElement("input");
nf.type="text";
el.appendChild(nf);
}
</script>
<p>
<form id="testform">
<label onclick="add();"> create</label>
</form>
</p>
</body>
</html>
DEMO

Categories