Append Text to paragraph on button click in jquery - javascript

I am doing a web based calculator wherein I want to append each and every number pressed on to a paragraph, this is the paragraph to hold all the entered input <p id="display" class="col-10 table-bordered" style="height:20px"></p> then this is one of the buttons <button class="col-2" id="seven">7</button>
Then below is the jQuery code used to try and captured the data
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#seven").click(function () {
//document.getElementById('display').text('7') = $('#seven').text();
$("#display").append('7');
});
});
</script>
The problem is when I click on button 7, the number appears once on the display and disappears, I think it is refreshing or something, I cant seem to get the number to stick once it has been clicked, please help.

Related

Change <input> value and submit automatically via jquery

I am prototyping a way for a user to view all the data behind a visualization. Basically they would click on a point, a modal would pop up, and the table within modal would be dynamically filtered by a string submission. I've got almost everything working perfectly so far, but I can't get the filter to submit on value change.
The tables library I am using is DataTables, so I have been trying to test this with a small jquery script and some html buttons.
Currently my script is triggered on click of a specific button, it then opens the modal, finds the table's unique id and then the closest child that is an input element, and then it writes a string as that input's value.
Example Sript:
<script>
$('#test-button-2').on('click', function () {
var search_input = $("#x-data-modal").find('input:first');
search_input.val('May 16, 2018');
})
</script>
Relevant HTML:
<div class="modal fade" id="x-data-modal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="moday-body">
<div class='row'>
Search:<input type="search" class="form-control form-control-sm" placeholder=""
aria-controls="x-data-table">
</div>
<table id='x-data-table'>table stuff</table>
</div>
</div>
</div>
</div>
I cannot access the input directly as it is created by the DataTables library without a unique id, but this does the trick. Upon clicking the button the modal is opened and the relevant input is changed to the included string. But for some reason it doesn't submit. So basically the table opens with a canned search when I wanted to open with that canned search either executed or in the process of executing.
I've tried:
<script>
$('#test-button-2').on('click', function () {
var search_input = $("#x-data-modal").find('input:first');
search_input.val('May 16, 2018');
search_input.submit();
})
</script>
And similarly (using the built in DataTables search module):
<script>
$('#test-button-2').on('click', function () {
var search_input = $("#x-data-modal").find('input:first');
search_input.val('Apr 27, 2018');
var table = $('#x-data-table').DataTable();
search_input.on('change', function () {
table.search(this.value).draw();
console.log(('This was the search') + this.value);
});
console.log('Ran Whole Function');
});
</script>
You need to call the .submit() function on the form element, not the input element.
Solved this by watching the Event listener for the search and piggy-backing off the DataTables function. Ended up being much eaiser to locate the search with this as well.
<script>
$('#test-button-2').on('click', function () {
var table = $('#x-data-table').DataTable();
table.search('Jun 10, 2018').draw();
})
</script>

store 2 websites in 1 file and dynamically change between them

so this is a very vague question but say I had a single .html file and I wanted to store essentially 2 websites in the one file and swap to the 2nd page when a condition became true on the first page(preferably a onclick javascript event) kind of like an if statement(if condition A becomes true on page one: show page 2 else: continue to show page 1) would this be possible in just javascript or would I need the aid of other programming languages and what would be the most optimum way of going about this? I would want the data entered in an input feild on page 1 also available on page 2.
sorry for vague question and horrible formatting, this is my first ever question.
Joel, I don't have enough reputation to comment and so I must type an answer.
Local storage allows you to store a value (page number to display) within the user's local browser memory. This value can be tested for existence (useful for true/false conditions) and can be read (for meaningful values).
All you need to do is bind the creation of a simple local storage object (the page number to display). Bind the code to create the storage object to whichever event you want (such as a button click).
localStorage.setItem('entryPage', '2');
You will also need some code to read within the HTML file to decide what to display (via scroll, hidden and displayed DIV elements or whatever technique you are using).
if(localStorage.getItem('entryPage')) {
//show page two code
}
Check here for a full tutorial set:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
Below is a chrome-tested one-page solution just demonstrating the concept of the local storage part. You'll always be within the same HTML file, but load will show content one until you click the button and set local storage to display page 2, then any future load will be page two until you clear local storage.
<!DOCTYPE html>
<html>
<body>
<div id="main-container">
<div id="content-one" style="display:block;">
<p>This is page one content</p>
<button id="showTwo">Show Page 2</button>
</div>
<div id="content-two" style="display:none">
<p>this is content for page 2</div>
</div>
</div>
<script>
//this function actually swaps display
function swapper(){
document.getElementById('content-one').style.display = 'none';
document.getElementById('content-two').style.display = 'block';
}
//if the value exists in storage, swap them
if(localStorage.getItem('entryPage')) {
swapper();
}
//when button clicked, swap them and store value
var btn = document.getElementById("showTwo");
btn.addEventListener("click", function(){swapper();localStorage.setItem('entryPage', '2');}, false);
</script>
</body>
</html>
To clear local storage on Chrome, see LOCAL AND SESSION section here:
https://developer.chrome.com/devtools/docs/resource-panel#local-and-session-storage
And below is a version including a text-box which simply used the value of the local storage object to hold the data you wish to carry to content page 2. (Remember, if you have tested the first example above you must clear local storage to use this example below because otherwise it will never show you the first content pane).
<!DOCTYPE html>
<html>
<body>
<div id="main-container">
<div id="content-one" style="display:block;">
<p>This is page one content</p>
<input type="text" id="theInput"></input>
<button id="showTwo">Show Page 2</button>
</div>
<div id="content-two" style="display:none">
<p>this is content for page 2</div>
<p id="theOutput"></p>
</div>
</div>
<script>
//this function actually swaps display and shows the value from page 1 textbox
function swapper(theValue){
document.getElementById('content-one').style.display = 'none';
document.getElementById('content-two').style.display = 'block';
document.getElementById('theOutput').innerText = theValue;
}
//if the value exists in storage, swap them and pass on the value of textbox
if(localStorage.getItem('entryPage')) {
swapper(localStorage.getItem('entryPage'));
}
//when button clicked, swap them and store value
var btn = document.getElementById("showTwo");
btn.addEventListener("click", function(){
var theData = document.getElementById("theInput").value;
swapper();
localStorage.setItem('entryPage', theData);
}, false);
</script>
</body>
</html>

Include different .php files in JS popup

I have multiple buttons which currently redirect to different pages for users to perform a single action and they would then need to click another button whilst on the confirmation page to go back where they were before. This is old school and inconvenient...
What I would like to do is create 1 single pop-up box which would get triggered (appear) when any of those buttons are clicked. Inside the box, I want the relevant .php file to appear so users can confirm their action and the page would then reload and display a confirmation message.
Example:
"Delete" button needs to trigger the confirmation-popup.php to appear with the delete.php file included in it so users can confirm the deletion.
"Cancel" button needs to trigger the confirmation-popup.php to appear with the cancel.php file included in it so users can confirm the cancellation.
Here's what I've done:
- Created the pop up and included it on their Account page (that's where all the buttons are).
- Added a JS which passes through the button ID to trigger the popup
When either of the buttons is clicked, the popup would appear fine.
I'm stuck at the stage where different "action".php files need to passed and included in the body of the popup. I know I could create multiple popups each for its relevant action, but we all know this isn't best practice and it's doubling up.
Any help would be appreciated!
Edit: Added code after the below comment
HTML:
<button class="button-small button-red" id="confirm-delete">Delete</button>
JS:
$(document).ready(function() {
$("#confirm-delete").click(function() {
if (!$(".confirm-popup").is(":visible")) {
$(".confirm-popup").fadeIn("slow");
return false;
}
});
});
PHP confirm_popup.php:
<div class="confirm-popup">
<?php include 'delete_auction.php'; ?>
</div>
You can open different iframes in the popup based on the button pressed. That will allow you to use one popup and you will just edit the iframe src attribute to the correct php page. For example you can add an HTML attribute to each button that holds the URL of the page that should be opened by the button. Then you will have some JS code that on the button press will read the attribute that holds the URL and puts it in the iframe src attribute inside the popup.
Something like this using jQuery:
<button class="myclass" cotent-url="delete.php">Delete</button>
<button class="myclass" cotent-url="save.php">Save</button>
<div class="popup"><iframe src=""></iframe></div>
<script type="text/javascript">
$('.myclass').click(function(){
$('.popup iframe').attr('src', $(this).attr('content-url'));
})
</script>
Or AJAX way:
<button class="myclass" cotent-url="delete.php">Delete</button>
<button class="myclass" cotent-url="save.php">Save</button>
<div class="popup"></div>
<script type="text/javascript">
$('.myclass').click(function(){
$.ajax({
url: $(this).attr('content-url'),
data: {},
success: function(response) {
$('.popup').html(response);
},
dataType: 'html'
});
})
</script>

JQuery losing initial click event when reloading a table via .load() after a .change() handler

I am working with a complex application where there are two divs each of which contain the HTML/JS of a separate page. Each div is loaded in a $(document).ready() script. The top div contains a table and the bottom div contains a form.
The two pages are bound (linked) in that if you click on a row in the table it highlights that town and loads that rows data into the form by refreshing the forms div. Also, if you change (edit) any of the fields in the data form it will automatically refresh the table by reloading the HTML for the table with the currently selected row in that table remaining selected.
Because of the design of the larger system I don't really have any control over the basic approach (two divs both being reloaded on the fly to reflect the changes in the other). Both files are actually not bound to each other but rather to a database which is used in the MVC design.
In my application everything is working just fine... click on a row at the top and you get the data below. Change a value in the form and then cause a change() event to fire (hit tab, click off the field, etc) and the table above is refreshed. C'est tres beaux.
Except... there is one small bug which is when you cause the change() event to fire by clicking on a row in the table everything works correctly except that the row you clicked on does not get the initial click event and the row does not get highlighted.
This is presumably because the refresh of the table page causes the click event to fail when it finally gets resolved (after the change() event). I figured that I could probably save the identity of the row that was clicked in a cookie or something and then on the ready() function of the load have it check but I can not for the life of me trap that initial event anywhere.
I've created a much simpler version of the problem which fails in the same way and created a fiddle at http://jsfiddle.net/AKirino/cdhqmp2z/.
Due to some problems with the fiddle not executing the ready() code in the table file I've moved all the js to the base file. I've also integrated the form portion into the main page to simplify things.
In the test code you can:
Click on a row in the table and see the text of that row appear in the lower window.
Change a value in the lower window, then hit tab or click off it and it will appear in the table.
However, if you change a field in the form then cause the change() event to fire by clicking on a row in the table, the table row does not highlight.
Is there any way to trap the initial event of clicking on the row before the page is refreshed?
Here is my original (pre fiddle) test code. I am working in Safari on OSX and using query-1.9.1.
CSS:
div {padding:1em; text-align:center;}
div.page_container {background-color:#C4C4C4; max-width: 80%; margin-left: auto; margin-right: auto;}
div.table_area {background-color:#ffffc0;}
div.working_area {background-color:#c00000;}
table, form {width:15em; margin:0 auto;}
tr.selected {background-color:#ffffff}
td {border: 1px solid; padding:.25em;}
BaseFile:
<html><head>
<meta charset='utf-8'>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<link rel="stylesheet" href="refreshTest.css" type="text/css" />
</head>
<body>
<script>
$(document).ready(
function( ) {
$('div.table_area').load('refreshTestTable.html');
$('input').change(function(event) {
var id = $(this).attr('id');
console.log('datachanged: '+id);
var myValue = $(this).val();
$('tr#'+id+' td').html(myValue);
$('div.table_area').load('refreshTestTable.html');
});
});
</script>
<div class='page_container'>
<div class='table_area'></div>
<div class='working_area'>
<form id='galleryForm'>
<label for='field1' id='field1_label' >Field1: </label><input id='field1' autocomplete="off" value='This is field 1' /><br />
<label for='field2' id='field2_label' >Field2: </label><input id='field2' autocomplete="off" value='This is field 2' /><br />
<label for='field3' id='field3_label' >Field3: </label><input id='field3' autocomplete="off" value='This is field 3' /><br />
</form>
<div id="console"> </div>
</div>
</div>
</body>
</html>
TableFile:
<html><head><script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script></head>
<body>
<script>
$(document).ready(
function( ) {
$('table').delegate('tr', 'click', function(evt){
var id = $(this).attr('id');
var myLogMsg = 'tr click: '+id;
console.log(myLogMsg);
$('tr').removeClass('selected'); // Unselect all
$(this).addClass('selected'); // Select clicked row
$('div#console').html(myLogMsg);
});
$('input').each(function(){
var myId = $(this).attr('id');
$('tr#'+myId+' td').html($(this).val());
});
});
</script>
<table>
<tr id='field1'><td>fill1</td></tr>
<tr id='field2'><td>fill2</td></tr>
<tr id='field3'><td>fill3</td></tr>
</table>
</body>
</html>
You need to change to on(). The delegate() handler has been deprecated (As of jQuery 1.7) -
$('table').on('click', 'tr', function(evt){
I've used the following example for buttons that have been loaded after initial page loaded.
$(document).on("click", ".button-class", obj.eventName);
// where obj.eventName is just a method on my js obj
// or
$(document).on("click", ".button-class", function(evt){
// do something
evt.preventDefault();
});
I update your JSFiddle in here, http://jsfiddle.net/gschutz/cdhqmp2z/13/. Your question is too long, I don't know if I understand it.
A good practice here is to make a function for select, and unselect and not only addClass.
You are right, the jquery is not so cleaver, you have to save this information in another variable. A good practice, is to work with just data on the backend (like REST), and you don't need to order again that some element is selected, because the <tr class="selected"> will not change (if you don't reload it). If you are interest in another lib to make complex app, try angularjs.org or d3js.org.
Hope this can help you.

target to a div without reloading the page in javascript

i wrote a web page that included some stuff. There, i need to create a input text box after clicking on a button, but it will be at the bottom due to existing stuff and i can't see the input box as it is in the out of visible area.there i'v to scroll down to find that.I tried with focus method , it focuses to the input box, it is unable to take the input box to visible area.in the top , i'v some javascript stuff .so i need to do this without refreshing.Here is the code snippet i'v tried.
<script>
function create(){
var inputBox=document.createElement('input');
inputBox.setAttribute('id','myInput');
var body=document.getElementsByTagName('body')[0];
body.appendChild(inputBox);
document.getElementById('myInput').focus();
}
</script>
<body>
<button onclick="create()">Click me</button>
</body>
Can anyone help me !
Yes, you are inserting the text input as the last element in body. If you want it to appear at a specific place, create a placeholder for it. For instance:
<script>
function create(){
var inputBox=document.createElement('input');
inputBox.setAttribute('id','myInput');
var wrapper=document.getElementById('wrapper');
wrapper.appendChild(inputBox);
inputBox.focus();
}
</script>
<body>
<button onclick="create()">Click me</button>
<div id="wrapper"></div>
</body>
You need a anker:
<a name="button"></a>
<button onclick="create()">Click me</button>
Then you can jump to it
location.href = 'http://yourpage#button'
The page will not reload if you jump to an anker on the same page.
Well you can always have the input in the HTML markup , and make it visible when clicking the button .
Also replacing the
body.appendChild
with
body.insertBefore(inputBox,body.firstChild);
should do what you want .

Categories

Resources