I have been working on a small contact form for a webpage and I used some code from a website to create the form. My problem is that the submit button wants to post the data and all is the submit button to create a message alert, and also redirect to another page after the message appears..
Any help would be greatly appreciated! Thanks!
here is the JS:
// Fetching HTML Elements in Variables by ID.
var x = document.getElementById("form_sample");
var createform = document.createElement('form'); // Create New Element Form
createform.setAttribute("action", ""); // Setting Action Attribute on Form
//createform.setAttribute("method", "post"); // Setting Method Attribute on Form
x.appendChild(createform);
var heading = document.createElement('h2'); // Heading of Form
heading.innerHTML = "Contact Form ";
createform.appendChild(heading);
var line = document.createElement('hr'); // Giving Horizontal Row After Heading
createform.appendChild(line);
var linebreak = document.createElement('br');
createform.appendChild(linebreak);
var namelabel = document.createElement('label'); // Create Label for Name Field
namelabel.innerHTML = "Your Name : "; // Set Field Labels
createform.appendChild(namelabel);
var inputelement = document.createElement('input'); // Create Input Field for Name
inputelement.setAttribute("type", "text");
inputelement.setAttribute("name", "dname");
createform.appendChild(inputelement);
var linebreak = document.createElement('br');
createform.appendChild(linebreak);
var emaillabel = document.createElement('label'); // Create Label for E-mail Field
emaillabel.innerHTML = "Your Email : ";
createform.appendChild(emaillabel);
var emailelement = document.createElement('input'); // Create Input Field for E-mail
emailelement.setAttribute("type", "text");
emailelement.setAttribute("name", "demail");
createform.appendChild(emailelement);
var emailbreak = document.createElement('br');
createform.appendChild(emailbreak);
var messagelabel = document.createElement('label'); // Append Textarea
messagelabel.innerHTML = "Your Message : ";
createform.appendChild(messagelabel);
var texareaelement = document.createElement('textarea');
texareaelement.setAttribute("name", "dmessage");
createform.appendChild(texareaelement);
var messagebreak = document.createElement('br');
createform.appendChild(messagebreak);
var submitelement = document.createElement('input'); // Append Submit Button
submitelement.setAttribute("type", "submit");
submitelement.setAttribute("name", "dsubmit");
submitelement.setAttribute("value", "Submit");
createform.appendChild(submitelement);
If I'm understanding your question correctly, you want the page to verify before submitting, correct?
If so, you can add a listener which optionally cancels the submit action.
createform.addEventListener("submit", function() {
return confirm("Continue?");
});
You can add an event listener for submit event on submit button. Prevent it's default behavior, show an alert and then redirect to whatever page you want
createform.addEventListener("submit", function(e) {
e.preventDefault();
var msg = window.confirm("Want to go to other page?");
if (msg) {
window.location.href = "url";
}
})
Related
I have a group of dynamically generated input fields. I want to loop through all of them and check if the user has indeed written something on them. If all fields have been filled, activate the button, otherwise, desactivate it. Code is really long, so here is the most important part :
//Here is the loop that creates the number of inputs to create based on what the user enters:
(CourseObject.course_array).forEach((evaluation,value) => {
const percentage_value = CourseObject.each_evaluation_value[value];
//Some lists
const li_inputs = document.createElement('li');
li_inputs.id = ((`${evaluation}-of-${CourseName}-input-li`.replace(/°/g, "")).replace(/ /g, "")).toLocaleLowerCase();
li_inputs.className = "list-group-item";
(document.getElementById(`${CourseName}-input-ul`).appendChild(li_inputs));
//Here starts the important stuff, creation of the inputs and attributes
const text_input = document.createElement('input');
text_input.type = 'text';
text_input.placeholder = `Nota de ${evaluation} (${percentage_value}%)`;
text_input.id = ((`${evaluation}-of-${CourseName}-input-text`.replace(/°/g, "")).replace(/ /g, "")).toLocaleLowerCase();
text_input.className = 'form-control grade-input';
(document.getElementById(((`${evaluation}-of-${CourseName}-input-li`.replace(/°/g, "")).replace(/ /g, "")).toLocaleLowerCase())).appendChild(text_input);
}
);
//Creating the button
const SendAndShow = document.createElement('button');
SendAndShow.textContent = 'Calcular';
SendAndShow.id = 'send-and-show-button';
SendAndShow.disabled = true; //Desactivated from the beggining
SendAndShow.className = 'btn btn-dark';
document.getElementById('second-column').appendChild(SendAndShow);
//Here I want to loop through the inputs. If they are all filled, SendAndShow.disabled = false
//A random event set to be activated once the button is clicked
document.getElementById('send-and-show-button').onclick = function() {
.
. //Something to do
.
}
I have tried querySelectorAll and getting the element by class but I can't seem to be able to hack it, any suggestions?
Note : I would like a pure JS answer, no JQuery.
You can use the onchange method in every input element, then check the values of inputs with FormData
const form = document.querySelector('#form')
function getFormData() {
formData = new FormData(form)
console.log(formData.entries())
}
text_input.onchange = function(){
getFormData()
}
<form id='form'></form>
for dynamic element add listener to the parent or body then check your input elements
createInput.addEventListener('click', function() {
let input = document.createElement('input')
myform.prepend(input)
submit.setAttribute('disabled', '')
})
// the parent
myform.addEventListener('input', function(el) {
if (el.target.tagName != 'INPUT') return;
// chack all input
let allFilled = true
document.querySelectorAll('#myform input').forEach(function(input) {
if (!input.value)
allFilled = false;
})
// set the button state
if (allFilled)
submit.removeAttribute('disabled')
else
submit.setAttribute('disabled', '')
})
input{display:block;margin:10px;}
<button id="createInput">Create input</button><br><br>
<form id="myform">
<button id="submit" disabled>Submit</button>
</form>
I am pretty new to Javascript. I am trying to add a form element to my Javascript Quiz results page.
function viewResultPage() {
console.log("viewResult Page: ", currentQuestionIndex, " ", timeleft);
// inner html Sets or returns the content of an element
welcometxt.innerHTML = ""
var allDoneEl = document.createElement("span");
allDoneEl.innerHTML = "Quiz is over and final score is: " + timeleft;
welcometxt.appendChild(allDoneEl);
// Create a form
const f = document.createElement("form");
// Add it to the document body
document.body.appendChild(f);
}
What I am trying to do is following the results page showing "your score is "
I need a form element for the users to enter their initials and submit.
const f = document.createElement("form");
//Add an input element to form
const input = document.createElement("input");
f.appendChild(input);
// Add it to the document body
document.body.appendChild(f);
// create a form for accepting the initial
var inputForm = document.createElement("form");
inputForm.setAttribute("id", "inputForm");
//Add an input element to form
var inputText = document.createElement("input");
inputText.setAttribute("type", "text");
inputText.setAttribute("id", "initialstext");
inputText.setAttribute("placeholder", "Enter your initials");
inputForm.appendChild(inputText);
// Add it to the document body
scoresSection.appendChild(inputForm);
// create a button for submitting the form
var submitBtn = document.createElement("button");
submitBtn.setAttribute("id", "submitBtn");
submitBtn.setAttribute("style", "float: center; position: relative;");
submitBtn.innerHTML = "Submit";
scoresSection.appendChild(submitBtn);
I tried this and it worked. Thank you #MrCano369
everything working as my desire but when I click on book room button it can not generate input field for me but its shows as [object HTMLFormElement] here is my code
function booking(roomBooking){
var f = document.createElement("form");
var in1 = document.createElement("input");
in1.type = "text";
in1.name = "user_name";
in1.id = "user_name1";
f.appendChild(in1);
document.getElementById("name").innerHTML=f;
}
I want to show form when I clicked on book room button.
Here you are:
You should just apply your f variable to "#name" element by using appendChild() function, because "f" it's an object and you cannot directly use it.
function booking(roomBooking) {
var f = document.createElement("form");
var in1 = document.createElement("input");
in1.type = "text";
in1.name = "user_name";
in1.id = "user_name1";
f.appendChild(in1);
document.getElementById("name").appendChild(f);
}
I am trying to create a form that when submitted will just output the two values to the console. However, when I run it, only the email field is being displayed and the name field is just showing 'undefined'.
I have created a JSFiddle of what I have so far.
https://jsfiddle.net/hbzxcvjj/1/
JS:
var name = document.getElementById("name");
var email = document.getElementById("email");
var submitButton = document.getElementById("btn-signup");
var sendInfo = function(){
console.log(name.value);
console.log(email.value);
}
submitButton.onclick = sendInfo;
try moving your variable definitions into the function, this is how it should look:
var submitButton = document.getElementById("btn-signup");
var sendInfo = function(){
var name = document.getElementById("name");
var email = document.getElementById("email");
console.log(name.value);
console.log(email.value);
}
submitButton.onclick = sendInfo;
https://jsfiddle.net/hbzxcvjj/2/
see the working fiddle
Try with alternate method:
submitButton.addEventListener("click", sendInfo);
I used Javascript to dynamically add textbox in order for the user to add more items in one process. Here's the code that add textboxes:
<script type="text/javascript">
var quantity = document.getElementById('quantity');
var item = document.getElementById('item');
var serial = document.getElementById('serial');
var property = document.getElementById('property');
document.getElementById('add').onclick = function () {
var input = document.createElement('input'),
div = document.createElement('div');
input.type = "text";
input.setAttribute("name", "quant");
div.appendChild(input);
quantity.appendChild(div);
var input2 = document.createElement('input'),
div2 = document.createElement('div');
input2.type = "text";
input2.setAttribute("name", "items");
div.appendChild(input2);
item.appendChild(div);
var input3 = document.createElement('input'),
div3 = document.createElement('div');
input3.type = "text";
input3.setAttribute("name", "serno");
div.appendChild(input3);
serial.appendChild(div);
var input4 = document.createElement('input'),
div4 = document.createElement('div');
input4.type = "text";
input4.setAttribute("name", "proper");
div.appendChild(input4);
property.appendChild(div);
};
</script>
When the user clicks the "Add Text" button, one set (four textboxes) will appear. My problem is even if the user clicks and inputs data into those textbox, it will only insert one set of data (which was the last set of input). Its because of the "name" of the textbox are the same. How can I insert those multiple data? Or how can I set a unique name for the added textbox in order to insert them into the database?
You'll want to change the names with a [] appended to it. This will pass an array to the PHP on form submit.
input.setAttribute("name", "quant[]");
To get the values in PHP,
$quant_values = $_GET['quant']; // array of values
$value_one = $quant_values[0];
You will need to implement a loop to iterate through the values.