JavaScript code not working when displaying value of html element - javascript

I want to display details in div element(id="displayStoragevol2"). Why below code is not working
<hr>
<h3>LocalStorage App Vol-2</h3>
<label>First Name: </label><input type="text" id="firstNamevol2">
<label>Last Name: </label><input type="text" id="lastNamevol2">
<button type="submit" id="fetchDetailsvol2">Submit</button>
<div id="displayStoragevol2"></div>
<hr>
<script>
/*LocalStorage Vol 2*/
document.getElementById('fetchDetailsvol2').addEventListener('click', fetchFunction);
var firstNamevol2 = document.getElementById('firstNamevol2').value;
var lastNamevol2 = document.getElementById('lastNamevol2').value;
var displayStoragevol2 = document.getElementById('displayStoragevol2');
function fetchFunction(){
displayStoragevol2.innerHTML = firstNamevol2 + lastNamevol2;
}
</script>

You read the values from the inputs when the page loads. At that time they are blank.
If you want to read the values when the element is clicked, you need to do so inside the event handler function.

Your script section should be updated as follows,
<script>
document.getElementById('fetchDetailsvol2').addEventListener('click', fetchFunction);
var displayStoragevol2 = document.getElementById('displayStoragevol2');
function fetchFunction(){
var firstNamevol2 = document.getElementById('firstNamevol2').value;
var lastNamevol2 = document.getElementById('lastNamevol2').value;
displayStoragevol2.innerHTML = firstNamevol2 + lastNamevol2;
}
</script>
Since variable firstNamevol2 and lastNamevol2 were in global scope those variables are assigned the values when the page is loaded not when the button is clicked.

You should take care when you are declaring your variables in the process; they should be inside the click event handler.
Below is my working code (with variable and class names tidied).
HTML:
<h3>Input Data</h3>
<label>First Name:</label> <input type="text" id="firstName">
<label>Last Name:</label> <input type="text" id="lastName">
<button type="submit" id="fetchDetails">Fetch Details</button>
<hr>
<h3>Display Data:</h3>
<span id="displayFirstName"></span>
<span id="displayLastName"></span>
<hr>
Javascript:
function fetchData() {
// On click of Fetch Details
document.getElementById("fetchDetails").addEventListener("click", function(event){
event.preventDefault();
// Assign values to variables
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
// Display values in results field
document.getElementById("displayFirstName").innerHTML = firstName;
document.getElementById("displayLastName").innerHTML = lastName;
});
}
fetchData();
Codepen here

Related

Reset (reset to previous value) only the form fields that are changed

I need to reset only the form fields that are changed (reset to previous value).
I tried to use the reset but it completely resets the entire form and I don't need this.
How can I do this?
function clearResult() {
document.getElementById("save").reset();
}
<div class = "container">
<form method="post" id="save" onload="onLoad()">
<div class="field">
<label for="id"> ID:</label>
<input type="number" id="id" name="id" />
</div>
<div class="field">
<label for="type"> Fragment Type: </label>
<input type="text" id="type" name="type" />
</div>
<div class="button">
<button type="submit" class="full">Save changes</button>
<input type="button" value="Cancel" onclick="clearResult()" />
</div>
</form>
</div>
First of all you should to store the predefined values of form elements to set them back when you want to reset them back.
Then you can use this globally defined initial values to set them back whnever reset event occurs.
var id, type;
const form = document.getElementById('save');
document.onload = (event) => {
id = form.id.value;
type = form.type.value;
};
function clearResult() {
form.id.value = id;
form.type.value = type;
};
It was simple. When page load just get values from that fields.
Make with document.onload:
var firstValue = document.getElementById("yourFieldId").value;
After form submit get values like below:
var currentValue = document.getElementById("yourFieldId").value;
And after submit in reset check if CURRENT VALUES equal with VALUES FROM FIRST TIME
Example
if(firstValue != currentValue){
document.getElementById("yourFieldId").value = firstValue;
}

Second input box in form doesn't work second time

I have this form:
<form id="addChore" method="post" action="allocate.php">
<label>Name of new chore:</label>
<input type="text" id = "choreName" name="choreName">
<p></p>
<label>Description:</label>
<input type="text" id="description" name="description">
<p></p>
<label>Frequency:</label>
<select id="frequency" name="frequency">
...
</select>
<input type="submit" value="Submit">
</form>
and this jQuery
$(document).ready(function(){
$("#addChore").on('submit',function(e){
e.preventDefault();
$("#error").empty();
var name = $("#choreName").val();
console.log(name);
var description = $("#description").val();
console.log(description);
var frequency = $("#frequency").val();
console.log(frequency);
var message=("Please fill all fields");
// $('#addChore')[0].reset();
if (!name || !description){
$("#error").append("<p>"+message+"</p>");
return false;
}
else{...}
but when I try and use the form a second time, description is empty in the log, while name and frequency accept a new input. I have tried resets and .val("") but nothing seems to change this. Any help? :/
Turns out I had another element with the same id, but defined in php in a separate script

Google Sheets script UserForm - Send Data from Form to Spreadsheet- userform fields not handled correctly

I am new to google scripting. I have followed some tutorials online and created a user form which has 4 input:
company name, qty, agent and comment. The only goal here is to copy data from user form to spread sheet. I have written the following html and functions but data does not get populated after button add is clicked.
I know the addRowData function is working when correct input gets to it. So either I am not population rowData correctly or EventListener does not work correctly. Can anybody please help me find where the issue is?
function addNewRow(rowData) {
const currentDate=new Date();
const ss=SpreadsheetApp.getActiveSpreadsheet();
const ws=ss.getSheetByName("Results");
ws.appendRow([currentDate, rowData.companyName,rowData.qty,rowData.agentName,rowData.commentText]);
return true;
}
<div class="container">
<div>
<div class="form-group">
<label for="company-name">Company</label>
<input type="text" class="form-control" id="company-name">
</div>
<div class="form-group">
<label for="number-boxes">Number of Boxes</label>
<input type="Text" class="form-control" id="number-boxes">
</div>
<div class="form-group">
<label for="agent-name">Agent</label>
<input type="text" class="form-control" id="agent-name">
</div>
<div class="form-group">
<label for="comment-text">Comment</label>
<input type="Text" class="form-control" id="comment-text">
</div>
<button class="btn btn-primary" id="mainButton">Add</button>
</div>
</div>
<script>
function afterButtonClicked(){
var companyName = getElementById("company-name");
var qty = getElementById("number-boxes");
var agentName = getElementById("agent-name");
var commentText = getElementById("comment-text");
var rowData={companyName: companyName.value,qty: qty.value,agentName: agentName.value,commentText: commentText.value};
google.script.run.withSuccessHandler(afterSubmit).addNewRow(rowData);
}
function afterSubmit(e){
var qty = getElementById("number-boxes");
qty.value="";
}
document.getElementById("mainButton").addEventListener("click",afterButtonClicked());
</script>
</body>
I would like to propose the following modification.
Modification points:
At document.getElementById("mainButton").addEventListener("click",afterButtonClicked());, the function is run by () of afterButtonClicked() at the load of HTML. In this case, please remove ().
About getElementById("###"), in this case, please add document like document.getElementById("###").
When above points are reflected to your script, it becomes as follows. I think that your Google Apps Script works.
Modified script:
In this case, please modify your Javascript as follows.
<script>
function afterButtonClicked(){
var companyName = document.getElementById("company-name");
var qty = document.getElementById("number-boxes");
var agentName = document.getElementById("agent-name");
var commentText = document.getElementById("comment-text");
var rowData={companyName: companyName.value,qty: qty.value,agentName: agentName.value,commentText: commentText.value};
google.script.run.withSuccessHandler(afterSubmit).addNewRow(rowData);
}
function afterSubmit(e){
var qty = document.getElementById("number-boxes");
qty.value="";
}
document.getElementById("mainButton").addEventListener("click",afterButtonClicked);
</script>
References:
EventTarget.addEventListener()
Document.getElementById()

taking form input value into a new created div "note"

I have a school project, where they asked us to create a form where you input values, and when you click submit, a new note will shoe and will be filled with the values from the form.
My problem is that I can't understand how to write the function that creates the notes with the values from the form.
I already did the form and the design for the page. Also started the function to create the note.
This is the form:
<form id="form1">
Mission Details: <textarea name="Details" rows="3" cols="20"></textarea> <br> <br>
Mission Due Date: <input type="Date" name="Date"> <br> <br>
Mission Due Time: <input type="Text" name="Time"> <br> <br>
<button type="button" onsubmit="createNote()"> Submit </button>
<button type="button" onclick="Clear()"> Clear </button>
</form>
This is the script i started:
function CreateNote(event) {
var form = event.currentTarget;
var details = form.Details.value;
var date = form.Date.value;
var time = form.Time.value;
}
var form = document.getElementById('form1');
form.onsubmit = CreateNote();
This is the div for the note and note content:
<div class="note">
<div class="noteDetails">
</div>
</div>
Eventually, the note will have a background from an image in a CSS file, and inside that note, it will have the values from the form.
1. Create a template for your note, lets say you display your text with <p></p>.
2. Leave it with empty values. Give it an id, lets call it "details".
3. After you have the desired values, use document.getElementById("details"), and fill the <p> with the value.
<div class="note">
<div class="noteDetails">
<p id="details"></p>
</div>
</div>
then in your JavaScript you can use
var stringInput = "Some String";
var detailsElement = document.getElementById("details");
detailsElement.innerHTML = " stringInput;
You can now use your div noteDetails. Inside it create three p elements with id details, date and time.
eg:
<div class="noteDetails">
<p id="details"></p>
<p id="date"></p>
<p id="time"></p>
</div>
Change your button element to:
<button type="button" onclick="createNote()"> Submit </button>
Note: your using createNote() in html and using CreateNote in JS
and inside your createNote function just add
function createNote() {
var form = document.getElementById('form1');
var details = form.Details.value;
var date = form.Date.value;
var time = form.Time.value;
var detailsPara = document.querySelector('#details');
detailsPara.innerText = details;
var datePara = document.querySelector('#date');
datePara.innerText = date;
var timePara = document.querySelector('#time');
timePara.innerText = time;
}
remove lines from your code
var form = document.getElementById('form1');
form.onsubmit = CreateNote();
UPDATE: if input values are to be shown immediately then add these to html
Mission Details: <textarea name="Details" rows="3" cols="20" oninput="createNote()"></textarea> <br> <br>
Mission Due Date: <input type="Date" name="Date" oninput="createNote()"> <br> <br>
Mission Due Time: <input type="Text" name="Time" oninput="createNote()"> <br> <br>

How to on click get 2 different data sets with the same class

I basically on click need to insert the data- into a form. The issue is that both forms use the same element classes and when I perform one function it inserts the data but as soon as I click to run the other function it clears the original data. Here is my code:
HTML
<div class="inbox-widget nicescroll mx-box">
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item" data-tag="Followers" data-social_type="twitter">
<p class="inbox-item-date">Click to add</p>
</div>
<div class="inbox-item" data-tag="Friends" data-social_type="twitter">
<p class="inbox-item-date">Click to add</p>
</div>
</a>
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item2" id="chosen_account" data-social_id="12345">
<p class="inbox-item2-date">Click to add social ID</p>
</div>
</a>
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item" id="chosen_account" data-social_id="6789">
<p class="inbox-item-date">Click to add social ID</p>
</div>
</a>
</div>
<form>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="input" id="social_id" type="text" name="social_id" />
<input type="input" id="social_type" type="text" name="social_type" />
<input type="input" id="chart_type" type="text" name="chart_type" value="line"/>
<input type="input" id="chart_tag" type="text" name="chart_tag"/>
</form>
My Jquery:
$('.inbox-item').click(function() {
var social_type_value = $(this).data('social_type');
var social_type_input = $('#social_type');
social_type_input.val(social_type_value);
var chart_tag_value = $(this).data('tag');
var chart_tag_input = $('#chart_tag');
chart_tag_input.val(chart_tag_value);
var social_id_value = $(this).data('social_id');
var social_id_input = $('#social_id');
social_id_input.val(social_id_value);
});
I also created a fiddle to show whats happening: https://jsfiddle.net/p18f3dow/1/
if i got your problem right, you'd want to use one function - but depending on the clicked element add different data... but don't overwrite the already entered data, when clicked element don't contains relevant data...
why not checking, if the data tag exists, in the first place:
$('.inbox-item').click(function() {
if ($(this).data('social_type')) {
var social_type_value = $(this).data('social_type');
var social_type_input = $('#social_type');
social_type_input.val(social_type_value);
}
if ($(this).data('tag')) {
var chart_tag_value = $(this).data('tag');
var chart_tag_input = $('#chart_tag');
chart_tag_input.val(chart_tag_value);
}
if ($(this).data('social_id')) {
var social_id_value = $(this).data('social_id');
var social_id_input = $('#social_id');
social_id_input.val(social_id_value);
}
});
this would be the quick and dirty solution, though.
better one would be like storing the complete clicked data objects and iterating through them, filling the correct fields. see https://jsfiddle.net/p18f3dow/4/
therefore you have to ensure that the part behing the data- in your html always matches your id in the form. (had to change it from data-tag to data-chart_tag)
then all you need is a simple function like that:
$('.inbox-item').click(function() { //when clicked
var stored_data = $(this).data(); //save everything in an object
for (var key in stored_data) { //iterate through the object
if (stored_data.hasOwnProperty(key)) {
$('#' + key).val(stored_data[key]) //create an id with #+key and insert the value
}
}
});

Categories

Resources