I am having a issue with HTML and jQuery programming.
I am making a bulletin board with HTML and jQuery, with 2 textboxes and a button.
$(document).ready(function(e) {
$('save').click(function() {
const name = $('name').val();
const words = $('words').val();
$.post(
"http://localhost:8000/board_write",
{
name: words
},
function(data, status) {
}
)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="0">
<tr>
<td class="vert" bgcolor="">
Name
</td>
<td>
<input class="name">
</td>
</tr>
<tr>
<td bgcolor="">
Anything you'd like to say
</td>
<td>
<textarea class="words" cols="40" rows="5" placeholder="please enter anything">
</textarea>
</td>
</tr>
<tr>
<td>
<input class="save" type="button" onclick="write()" value="Save">
</td>
</tr>
</table>
And, I also coded with jQuery to send the data of the two textboxes to localhost:8000, which is a node.js server to log the data to the console.
When I click the button, the page vanishes. What causes the situation? And, how can I solve the problem?
You have onclick = "document.write()"; that explicitly deletes the document . https://www.w3schools.com/jsref/met_doc_write.asp
Explanation: the code in onclick is scoped such: {window{document{element{}}}}; if you meant to implement a write() function, do so and invoke it by window.write(), or name it something differently to document.write. Otherwise, write() will de resolved to document.write().
Related
This question already has answers here:
How to save and retrieve contenteditable data
(2 answers)
Closed 1 year ago.
I have different content editable in my html file. I have a couple of labels, and a couple of tables with content editable as well.
I want to send the info to a database after user focus out, no buttons to trigger the action.
This is part of my html:
<label id="firstLabel" contenteditable="true">Hello</label>
<table id="firstTable">
<input type="hidden" name="userId" id="userid" value="<?php echo $userId ?">
<tr>
<td id="firstRow" name="firstRow" contenteditable="true">This is first row</td>
</tr>
</table>
<div class="footer" id="footer" contenteditable="true">Bottom message</div>
I'm new to programming, and I'm trying to figure the best way to get the contenteditable information, and send it to my database. I know I have to use Javascript, Ajax, and send it to a PHP file based on the information I've researched. The PHP part is not a problem for me, but I need a little help with the Javascript and AJAX parts because everything I tried so far has not retrieved any results.
Thank you.
A simple example of how to do this might be to assign a blur event listener bound to all elements that have the contenteditable attribute set and use fetch api to send the AJAX request using a FormData object to your backend PHP script.
const getparent=(e)=>{
let n=e.target;
while(n.tagName.toLowerCase()!='span' && n.className!='record'){
if(n.tagName=='BODY')return false;
n=n.parentNode;
}
return n;
}
document.querySelectorAll('[contenteditable="true"]').forEach(el=>{
el.addEventListener('blur',function(e){
let span=getparent(e);
if( !span )return;
let fd=new FormData();
fd.set('userid', span.querySelector('[name="userId"]').value );
fd.set('text', this.textContent );
fd.set('id', this.id );
fetch( 'https://www.example.com', { method:'post', body:fd, mode:'cors' })
.then( r=>r.text() )
.then( text=>{
console.log( 'Do something with returned response: %s',text )
})
})
})
.record{
display:block;
margin:1rem;
border:1px solid red;
padding:1rem;
}
<span class='record'>
<label id="label-1" contenteditable="true">Hello World</label>
<table>
<input type="hidden" name="userId" value="123456789">
<tr>
<td id="row-1" name="firstRow" contenteditable="true">This is first row</td>
</tr>
</table>
<div class="footer" contenteditable="true">A message from the Bottom</div>
</span>
<span class='record'>
<label id="label-2" contenteditable="true">World Hello</label>
<table>
<input type="hidden" name="userId" value="987654321">
<tr>
<td id="row-2" name="secondRow" contenteditable="true">This is second row</td>
</tr>
</table>
<div class="footer" contenteditable="true">A bottom from the Message</div>
</span>
It's not an "out of the box" answer, but a skeleton : you can listen for an element lost the focus, ie the user is no more typing in it.
let edit = document.getElementById("firstRow");
edit.addEventListener("blur", function(e) {
console.log("You can send to php");
// please have a look here for ajax : https://developer.mozilla.org/fr/docs/Web/Guide/AJAX
});
<label id="firstLabel" contenteditable="true">Hello</label>
<table id="firstTable">
<input type="hidden" name="userId" id="userid" value="<?php echo $userId ?">
<tr>
<td id="firstRow" name="firstRow" contenteditable="true">This is first row</td>
</tr>
</table>
<div class="footer" id="footer" contenteditable="true">Bottom message</div>
This function isn't working. Can anyone please help? When I press the validate button, nothing happens.
<script>
function validate()
{
int user = document.getElementById("uname");
if(user=="rohit")
document.getElementById("btnsubmit").value = "Sucess";
else
document.getElementById("btnsubmit").value = "Fail";
}
</script>
<body>
<div>
<table id="tbl-aut">
<tr>
<td colspan="2"><h2>Enter Login Details</h2></td>
</tr>
<tr>
<td >Username<span style="color:red">*</span></td>
<td><input type="text" ></td>
</tr>
<tr><td colspan="2" align="center"><input id="btnsubmit" type="button" value="Validate" onclick="validate()"><td></tr>
</table>
</div>
</body>
Nothing is happening because you have a few problems:
First, you have a syntax error. int is not a valid keyword in JavaScript. In JavaScript, data types are implicitly determined. You cannot explicitly specify a type (and there is no integer type in JavaScript anyway).
Next, you are attempting to check an object (the text field) against the value stored in the object. You need to access the value property of the text field to get the data entered into it.
Also, you are attempting to get an object with an id of uname, but you didn't set up that id in the text field at all.
Lastly, and this is more of a best-practice thing. Always wrap the true/false branches of your if statements with curly braces {}. Although it is syntactically OK to omit them when there is only one statement in the branch, this is a well-know bug magnet.
<script>
function validate() {
var user = document.getElementById("uname");
if(user.value =="rohit"){
document.getElementById("btnsubmit").value = "Sucess";
} else {
document.getElementById("btnsubmit").value = "Fail";
}
}
</script>
<body>
<div>
<table id="tbl-aut">
<tr>
<td colspan="2"><h2>Enter Login Details</h2></td>
</tr>
<tr>
<td >Username<span style="color:red">*</span></td>
<td><input id="uname" type="text" ></td>
</tr>
<tr><td colspan="2" align="center"><input id="btnsubmit" type="button" value="Validate" onclick="validate()"><td></tr>
</table>
</div>
</body>
I have table in my PHP file which is looks like this.
<div class="table-main" style="width:600px;" id="data-table-grid">
<table class="font order">
<tr>
<td>Item</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td colspan="4">
<span class="tdlist head">Party packs</span>
</td>
</tr>
<tr>
<td>
<span class="tdlist">Tango Pack</span>
</td>
<td>
$<span class="price">60</span>
</td>
<td>
<input type='text' class="item_input text-box" maxlength=9 name='item1' value='0' id='item2' style="width:60px;" />
</td>
<td>
<span></span>
</td>
</tr>
<tr>
<td>
<span class="tdlist">Gala Pack </span>
</td>
<td>
$<span class="price">100</span>
</td>
<td>
<input type='text' class="item_input text-box" maxlength=9 name='item2' value='0' id='item2' style="width:60px;" />
</td>
<td>
<span></span>
</td>
</tr>
I want to send this table output same as in mail with the filled data. I tried with this:
var msg = $("#data-table-grid").prop('outerHTML');
and I send mail and I got table format but I got an empty table. I want to get mail with the filled values.
Can anyone help me?
Turn the whole thing into a string and add it to the body of your mail. Change the "double quotes" too 'single quotes' and will work, just a little time consuming.
$mystring = "<Everything in here>";
If you have this php file seperate in directory than use
$str=file_get_contents(file path);
Now if you want to change some variable n this string tjan you can replace that too.
For examplr at first we define some special syntax in data file to be included such as ~~full_name~~.
Than now you can replace it dynamically here in mail sending page such as
$str = Str_replace("~~full_name~~", $fullName, $str);
And now you can use this above variable $str as body part of your email.
And one more important thing to keep in mind that in headera of your mail set content-type="text/html"
first of all, your table and div closing tags are missing. i hope in your original code you have them
also, #data-table-grid is your div not your table, so getting outer html will get the div as well, which you dont need.
you can do
var msg = $("#data-table-grid").html():
which will take the div's innerHTML which includes the table with values.
if you still need the div too however, refer to its parent's inner html as follows:
var msg = $("#data-table-grid").parent().html():
I have a form that I have made that uses jquery to detect when the button is pressed, as well as used to show the data without a page reload.
It is working perfect when the button is pressed, however when pressing enter the page refreshes and nothing happens. I have the button bound to the jquery, but I am not sure what to do to handle pressing enter.
Html:
<table border="0" width="100%" cellspacing="1" cellpadding="2" style="margin-bottom:20px;">
<tbody>
<tr class="infoBoxContents">
<td style="padding:20px;">
<table border="0" width="100%" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td width="50%">
<table width="100%">
<tbody>
<tr>
<td class="main">
<b>Calculate shipping</b>
<div class="smallText">Shipping Weight: 6lbs</div>
</td>
</tr>
<tr>
<td class="main" style="padding:10px;">Country:
<select name="ship_country_id" id="ship_country_id">
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
<br>Post code/ Zip code:
<input type="text" name="postcode" id="postcode_entry">
</td>
</tr>
</tbody>
</table>
</td>
<td class="main" width="50%" align="right">
<div class="contentText" id="shipping_method"></div>
</td>
</tr>
<tr>
<td>
<button type="button" id="estimate" style="cursor:pointer; width:110px; margin-left:10px; padding:5px;">
<span class="ui-button-text" style="float:left;">Calculate</span>
<span class="ui-button-icon-secondary ui-icon ui-icon-triangle-1-e" style="float:right;"></span>
</button>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
javascript:
$(function () {
$('#estimate').click(function () {
var postcode_entry = $('#postcode_entry').val();
var country_entry = $('#ship_country_id').val();
$("#shipping_method").html("<div style=\'margin:20px auto;width:100px;text-align:center;\'><img src=\'ext/jquery/bxGallery/spinner.gif\' /></div>").show();
$.get("checkout_shipping.php", {
country: country_entry,
refresh_quotes: "1",
postcode: postcode_entry,
zone_name: "canada"
},
function (data) {
$("#shipping_method").html(data);
}
);
});
});
That's because you need to find what happens on submit – this is the event that is called when you press enter, it doesn't trigger the click of the button.
I don't know what the ID of your form is, but you can do something like the following:
$("#myform").submit(function(e) {
e.preventDefault();
//do something
...
Use this instead of the button click event.
Instead of running your code when the button is clicked, run it when the form is submitted.
$('YOUR_FORM_HERE').submit(function() {
This will catch any means of submitting the form.
You can add this jQuery to bind to the same event:
$(document).on('keypress', function(e){
if(e.which === 13){
$('#estimate').click();
}
});
Though it would be better to separate the function that gets executed into a separate function, and call that, this will still work just fine.
I have code in html like this
<html>
<script type="text/javascript" src='LatihanKuisJs.js'></script>
<body>
<form name="kuis">
<table border="1" width="50%">
<tr>
<th colspan="2" >Celcius
</tr>
<tr>
<td align="center" width="80%">Kelvin</td>
<td align="center"><input type="text" id="kelvin">
</td>
</tr>
<tr>
<td align="center" width="80%">Reamur</td>
<td align="center"><input type="text" id="reamur"></td>
</tr>
<tr>
<td align="center" width="80%">Fahrenheit</td>
<td align="center"><input type="text" id="fahrenheit"></td>
</tr>
</table>
<input type="button" value="Calculate" onclick='calculateCelcius();'/>
<br/><br/>
<textarea rows="20" cols="90" id="textarea">
</textarea>
<br/><br/>
<input type="button" value="Clear" onclick='clear();'/>
</form>
</body>
</html>
and external javascript function like this:
function calculateCelcius(){
var kelvin = document.getElementById('kelvin');
var reamur = document.getElementById('reamur');
var fahrenheit = document.getElementById('fahrenheit');
var textarea = document.getElementById('textarea');
var hasil=(kelvin.value*1 + reamur.value*1 + fahrenheit.value*1);
textarea.value += hasil + '\n';
}
function clear(){
document.getElementById("textarea").value="";
}
When I tried to click the clear button on my page, the text area wasn't clear.
What's wrong? And what should I do?
Just rename your function from clear to something like clearTextarea and it will work.
The clear() method refers to obsolete document.clear() method, which is described at MDN as:
This method used to clear the whole specified document in early
(pre-1.0) versions of Mozilla. In recent versions of Mozilla-based
applications as well as in Internet Explorer and Netscape 4 this
method does nothing.
Also according to HTML5 specification:
The clear() method must do nothing.
References:
https://developer.mozilla.org/en-US/docs/DOM/document.clear
http://www.whatwg.org/specs/web-apps/current-work/multipage/obsolete.html#dom-document-clear
if you use a function like this one
function clearInput(element){
element.value="";
}
then in the input add this
onfocus="clearInput(this)"
this can be used multiple times for any text fields or text areas because the id of the object is passed where it calls the function from.
RKillah
Try adding javascript: before your function name when defining onclick event.
Something like this:
<input type="button" value="Clear" onclick='javascript: clear();'/>