I'm a newbie in coding and I need your expertise help.
This is my index.php codes
<div class="container">
<div class="row text-center"><h1>Stamford Network</h1></div>
<div class="row">
<div class="col-md-9">
<input type="textarea" name="text" placeholder="What's on your mind?" class="form-control" id="info" />
<input type="button" name="post" value="Post" class="btn btn-primary" id="post" />
</div>
<div class="col-md-3">
<h3>Hello,
<?php echo $_SESSION['username']; ?>
</h3>
<a class="btn btn-primary" href="login.php" role="button" >Logout</a>
</div>
</div>
<div class="row">
<div class="col-md-9">
<h4 id="display"></h4>
</div>
<div class="col-md-3"></div>
</div>
</div>
My .js code which link to the above index.php
window.onload = function() {
var button = document.getElementById("post");
button.addEventListener("click",
function() {
document.getElementById("display");
});
}
Can anyone tell me how create a post and display it without refreshing the page. Simply just click on the Post button then the information should appear below the posting form. While the words in the textarea should be gone when the button is clicked.
Please only show me the javascript way
var button = document.getElementById('post'),
info = document.getElementById('info'),
display = document.getElementById('display');
button.addEventListener('click', function(){
display.innerText = info.value;
info.value = '';
});
If you want the value to be uploaded to server for processing, you will need to add ajax XMLHttpRequest in the event listener.
Learn more about ajax here.
You should do it asynchronously.
First, use the tag to surround the data that you want to post:
<form>
...
</form>
Tutorial about forms:
https://www.w3schools.com/html/html_forms.asp
To post form asynchronously, you can use jquery or js. The simple and quick way is jquery. Here is a link to the documentation:
https://api.jquery.com/jquery.post/
There is an example at the end of the page of the jquery post doc's page, that explains how to use it, and basically do the thing that you wanted.
try this.
<script type="text/javascript">
window.onload = function() {
var button = document.getElementById("post");
button.addEventListener("click",
function() {
//document.getElementById("display");
document.getElementById('display').innerHTML = document.getElementById('info').value;
document.getElementById("info").style.display = "none";
});
}
</script>
Related
I have a code, who helps me switch between forms, however, when I submit the form, the page will reset and display first(default) tab again. Could anyone help me understand how I can make it so the tab I submit the form from stays there if the submision fails or even if the submision was successfull?
Forms are switching using a little JS code and are submited from a PHP POST method form.
Please find the code below:
Javascript responsible for switching between tabs:
function onTabClick(event) {
let activeTabs = document.querySelectorAll('.active');
// deactivate existing active tab
for (let i = 0; i < activeTabs.length; i++) {
activeTabs[i].className = activeTabs[i].className.replace('active', '');
}
// activate new tab
event.target.parentElement.className += 'active';
document.getElementById(event.target.href.split('#')[1]).className += 'active';
}
const elements = document.getElementsByClassName('nav-tab-element');
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', onTabClick, false);
}
CSS:
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
And here is the HTML forms:
<body>
<header>
<h1 class="main-header">
Add a New Product
</h1>
</header>
<main>
<ul id="nav-tab" class="nav">
<li class="active">
<a class="nav-tab-element" href="#books">Books</a>
</li>
<li>
<a class="nav-tab-element" href="#dvds">DVD's</a>
</li>
<li>
<a class="nav-tab-element" href="#furniture">Furniture</a>
</li>
</ul>
<form method="POST">
<div class="tab-content active" id="books">
<div class="book-tab">
<input type="text" name="sku" placeholder="test form for books" autocomplete="off">
</div>
<div class="btn">
<input type="submit" value="Submit">
</div>
</div>
</form>
<form method="POST">
<div class="tab-content " id="dvds">
<div class="dvd-tab">
<input type="text" name="sku" placeholder="test form for DVD" autocomplete="off">
</div>
<div class="btn">
<input type="submit" value="Submit">
</div>
</div>
</form>
<form method="POST">
<div class="tab-content " id="furniture">
<div class="furniture-tab">
<input type="text" name="sku" placeholder="test form for furniture" autocomplete="off">
</div>
<div class="btn">
<input type="submit" value="Submit">
</div>
</div>
</form>
</main>
<script src="main.js"></script>
</body>
Clicking submit submits the form data to the page given in the action attribute in form. If you don't put this attribute in (as you have not done) the default is to submit to the current page.
To fix the issue you have, I would suggest that rather than using vanilla form submit, you do you submission via ajax. Making an ajax call is quite simple in jQuery, so I recommend you look into that.
There is an event that is triggered when you send a form. You can prevent your page to reload doing the following:
event.preventDefault()
you can find more about here: https://www.w3schools.com/jsref/event_preventdefault.asp
or here https://www.w3schools.com/jquery/event_preventdefault.asp
All you have to do is add event.preventDefault() to the first line of your onTabClick(event) function. After you preventDefault you can run whatever logic you want right there.
The way vanilla html/js interact is: On form submission, the page attempts to send the info to a server and then it refreshes to update with new information. The rise of SPAs has shifted the desired behavior, and you need to override the browser default behavior to stop the refresh.
Adding Ajax/Axios would work as most of those API libraries have built in functions to override the default, but it is not necessary.
On the following page "https://www.capgemini.com/new-ways-to-accelerate-innovation". there are multiple sections with "Expand" button and when you click on expand button a form gets exposed. the issue here is am not able to attach click event to the "Submit" button.
I have tried using addeventlistener but the event is not getting assigned.
How do I do that, please advise.
https://www.capgemini.com/new-ways-to-accelerate-innovation
Expand Button is in the below code.
<div class="exp_article-header-bg">
<div class="exp_article-header-inner">
<h2 class="exp_article-header-title">TechnoVision 2017</h2>
<div class="exp_article-header-author"></div>
<div class="exp_article-header-lead">
<p>
TechnoVision 2017 gives you a framework to create a new digital story to solve problems and grasp new opportunities. Our 37 technology building blocks will help you to navigate the technology maze and give a clear direction to your business.
</p>
</div>
<div class="exp_article-header-expand">
**
<div class="exp_link exp_link--white exp_link--expand">
<span class="exp_link-label">EXPAND</span>**
<span class="exp_button-arrow exp_button-arrow--down"></span>
</div>
</div>
</div>
</div>
Form gets exposed when you click the above Expand button. The Submit button is in the form as highlighted below.
<form accept-charset="UTF-8" method="post" action="https://go.pardot.com/l/95412/2017-08-09/2tfbfg" class="form" id="pardot-form">
<style type="text/css">
form.form p label {
color: #000000;
}
</style>
<p class="form-field email pd-text required ">
<label class="field-label" for="95412_59459pi_95412_59459">Email Address</label>
<input type="text" name="95412_59459pi_95412_59459" id="95412_59459pi_95412_59459" value="" class="text" size="30" maxlength="255" onchange="piAjax.auditEmailField(this, 95412, 59459, 44072473);">
</p>
<div id="error_for_95412_59459pi_95412_59459" style="display:none"></div>
<p style="position:absolute; width:190px; left:-9999px; top: -9999px;visibility:hidden;">
<label for="pi_extra_field">Comments</label>
<input type="text" name="pi_extra_field" id="pi_extra_field">
</p>
<!-- forces IE5-8 to correctly submit UTF8 content -->
<input name="_utf8" type="hidden" value="☃">
<p class="submit">
<input type="submit" accesskey="s" value="Submit Now">
</p>
<script type="text/javascript">
//<![CDATA[
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href") && !anchor.getAttribute("target")) {
anchor.target = "_top";
}
}
//]]>
</script>
<input type="hidden" name="hiddenDependentFields" id="hiddenDependentFields" value="">
</form>
Have CSS display:none; for the element which needs to be expanded. when expand is clicked call a javascript function which checks if the element is hidden , if hidden change the CSS display: block;.
Check the below working code.
<body>
<div class="exp_article-header-bg">
<div class="exp_article-header-inner">
<h2 class="exp_article-header-title">TechnoVision 2017</h2>
<div class="exp_article-header-author"></div>
<div class="exp_article-header-lead"><p>TechnoVision 2017 gives you a framework to create a new digital story to
solve problems and grasp new opportunities. Our 37 technology building blocks will help you to navigate the
technology maze and give a clear direction to your business.</p>
</div>
<div class="exp_article-header-expand">
**
<div class="exp_link exp_link--white exp_link--expand">
<button onclick="myFunction()" class="exp_link-label">EXPAND</button>
**
<span class="exp_button-arrow exp_button-arrow--down" id="expandDiv"
style="color: #000066; background-color: gainsboro;display: none;">I Got Expanded</span></div>
</div>
</div>
</div>
</body>
Javascript function:-
<script>
function myFunction() {
var x = document.getElementById('expandDiv');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
check on plnkr: https://plnkr.co/edit/MWKYxmV6Jk2eId3Owt2u?p=preview
where is ur form opening? if u're usingjquery, just target the form id and do .submit()
You're going to want to use the 'onsubmit' event listener, most likely with a preveninstead of a click event.
document.querySelector("#submit-button").addEventListener("submit", function(event) {
//your stuff here
event.preventDefault();
}, false);
I have an form in my web app that is displayed via data-toggle. I'm altering the behavior of the submit event because I want to submit data without reloading the page. I can submit the form successfully and the toggle folds as expected, but afterwards, I can no longer collapse the form to use it again. What am I doing wrong?
Here is how I control the submit event
$('form').submit(function(event){
//event.preventDefault();
console.log('submit ' + $("input[name=personName]").val());
//console.log('submit ' + $('#personName').val());
//socket.emit('add', $('#personName').val());
socket.emit('add', $("input[name=personName]").val());
//$('#personName').val('');
$("input[name=personName]").val('');
//$("#add-person-panel").toggle();
$("div[id=add-person-panel]").toggle();
$("div[id=add-person-panel]").addBack('aria-expanded','false');
//$("input[name=personName]").toggle();
//$('#add-person-panel').attr('aria-expanded','');
//socket.emit('add', $('input[name=personName]'));
//$('input[name=personName]').val("");
return false; //do not let the page refresh on submit
});
form
<div class="panel panel-default">
<div class="panel-heading">
<%
if (hasKioskPermissions === true || hasDigmaKioskPermissions === true){ %>
<a data-toggle="collapse" href="#add-person-panel" class="collapsed">
"Add Person To Local Queue"
::after
</a>
<% } else { %>
<a data-toggle="collapse disabled" href="#add-person-panel" class="collapsed">
"Add Person To Local Queue"
::after
</a>
<%}%>
</div>
<div id="add-person-panel" class="panel-body collapse">
<form data-parsley-validate="" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5 col-xs-8">
<input name="personName" type="text" maxlength="40" placeholder="Enter name" required class="form-control" autocomplete="off">
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="submit" data-loading-text="Adding..." class="btn btn-lg btn-block btn-primary">Add</button>
</div>
</div>
</form>
</div>
</div>
Use $('div#add-person-panel') instead of $("div[id=add-person-panel]").
What is the template type? It's not plain html. There are <% %> in the code.
Are you trying to use server-side sockets in browser (socket.emit(...))?
UPD
Did you initialize your socket before using?
There is an example from docs:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' }); });
</script>
The problem was that I was not using the same plugin (from bootstrap) to close as I did with open. This is necessary since the plugin tracks it's own state.
before:
$('div#add-person-panel').toggle();
after:
$('div#add-person-panel').collapse('hide');
minimal solution below:
$('form').submit(function(event){
event.preventDefault();
console.log('submit ' + $("input[name=personName]").val());
$("input[name=personName]").val('');
$('div#add-person-panel').collapse('hide');
$('div#add-person-panel').addBack('aria-expanded','false');
return false; //do not let the page refresh on submit
});
I want to make a field that only shows up after a button click.
Heres my code so far:
<div class="control-group" style="display:none" id="passwordfield">
<label class="control-label">Password:</label>
<div class="controls"><input id="pw" type="password"></div>
</div>
The "display:none" makes it invisible, after that I have my button and a javascript which should change the display to "block", thus making it visible again.
<div style="padding-left: 160px;padding-bottom:20px">
<button class="btn btn-primary" onclick="showPWField()">Log-In</button>
<script>
function showPWField() {
document.getElementByID("passwordfield").style.display = "block";
}
</script>
</div>
But it just doesnt work. The function gets called I tested that with an alert, but I just can't change the style :/
Thanks for help in advance
the error is that getElementByID does not exist, you should use getElementById:
function showPWField() {
document.getElementById("passwordfield").style.display = "block";
}
<div class="control-group" style="display:none" id="passwordfield">
<label class="control-label">Password:</label>
<div class="controls"><input id="pw" type="password"></div>
</div>
<div style="padding-left: 160px;padding-bottom:20px">
<button class="btn btn-primary" onclick="showPWField()">Log-In</button>
<script>
function showPWField() {
document.getElementById("passwordfield").style.display = "block";
}
</script>
</div>
Javascript is a case sensitive,the method you used is getElementByID() won't work in javascript, better to use getElementById()
function showPWField() {
document.getElementById("passwordfield").style.display = "block";
}enter code here
I'm trying to use CasperJS to upload images to a web-form.
My form looks something like this:
<form action="" method="POST" enctype="multipart/form-data" class="form-vertical">
...
<legend>Campaign Banner</legend>
<div class="control-group image-field ">
<label class="control-label">Now Large</label>
<div class="controls">
<div class="file-field"><input id="id_now_large_image" name="now_large_image" type="file"></div>
<div class="image-preview"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group image-field ">
<label class="control-label">Now Medium</label>
<div class="controls">
<div class="file-field"><input id="id_now_medium_image" name="now_medium_image" type="file"></div>
<div class="image-preview"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group image-field ">
<label class="control-label">Now Small</label>
<div class="controls">
<div class="file-field"><input id="id_thumbnail_image" name="thumbnail_image" type="file"></div>
<div class="image-preview now-small"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
The submit button looks like this:
<div class="form-actions">
<button type="submit" class="btn btn-small ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text">Save changes</span></button>
</div>
I've put a Gist of the full HTML here: https://gist.github.com/victorhooi/8277035
First, I've tried using CasperJS's fill method:
this.fill('form.form-vertical', {
'now_large_image': '/Users/victor/Dropbox/CMT Test Resources/Test Banners/Default Banners/now_large.jpg',
}, false);
this.click(x('//*[#id="content-wrapper"]//button/span'));
I also did a this.capture(), and I saw that the file field had been filled in:
I'm not using the fill method's inbuilt submit, but I'm clicking on the submit button myself:
this.click(x('//*[#id="content-wrapper"]//button/span'));
I then do another capture, and I can see that the form has been submitted:
However, the image doesn't seem to have been uploaded at all.
I've also tried using PhantomJS's uploadFile() method:
this.page.uploadFile('input[name=now_large_image]', '/Users/victor/Dropbox/CMT Test Resources/Test Banners/Default Banners/now_large.jpg');
and then clicking on the submit button as well.
Same issue - the form field gets filled in - however, the image itself doesn't seem to get submitted.
Any ideas on how I can get the images to upload correctly here?
Since you are filling and submitting successfully, try a Wait command on the click.
casper.then(function() {
//+++ form fill here
//waits 1 sec
this.wait(1000, function() {
this.click(x('//*[#id="content-wrapper"]//button/span'));
});
});
Try this.
casper.thenOpen('about:blank', function(){
this.evaluate(function(){
var action = 'upload.php'
var html = '<form action="'+action+'" method="post" enctype="multipart/form-data">'
html += '<input type="file" name="files[]" multiple="multiple">'
html += '<button type="submit">Submit</button>'
html += '</form>'
document.write(html)
})
this.fill('form',{
'files[]': 'file.txt'
}, true)
this.waitFor(function(){
var uri = casper.evaluate(function(){
return document.documentURI
})
if ( 'about:blank' === uri ){
return false
}
return true
})
})