display two id# in same success message after form submit - javascript

i am trying to display text field val along with the val of a select field in a success message after form has submitted
This retuns the select field val. how would i store and add another val in same string
<script>
// when the DOM is ready
$(document).ready(function() {
// store a reference to the select field
const $budget = $('#budget');
// store budget
const $bookingForm = $('#booking-form');
// store success text field in the $successText variable
const $successText = $('.insert-success-text');
let customSuccessMessage = $budget.val();
// select field changes
$budget.change(function(){
// assign the new selected option
customSuccessMessage = $(this).val();
});
// when the form's submit button is clicked
$bookingForm.submit(function(e){
// if
if(customSuccessMessage){
// find .insert-success-text and add this text
$successText.text(`Thank you 'Thank you **text field val*** for your intrest in a ${customSuccessMessage}`);
// then submit the form
return true;
}
else{ // else if no option was selected
// focus on the select field
$budget.focus();
// stop form submission
return false;
}
});
});
</script>

I modified the code above.
<script>
$(document).ready(function() {
const $budget = $('#budget');
const $textField = $('#text-field');
const $bookingForm = $('#booking-form');
const $successText = $('.insert-success-text');
let customSuccessMessage = $budget.val();
$budget.change(function(){
customSuccessMessage = $(this).val();
});
$bookingForm.submit(function(e){
if(customSuccessMessage){
$successText.text(`Thank you ${$textField.val()} for your interest in a ${customSuccessMessage}`);
return true;
}
else{
$budget.focus();
return false;
}
});
});
</script>

Related

From element to element script

how to pass from a function to another function? (script>script) <= element
how do I pass the value of the field validator into the second function?
<script>
$('#card_number').validateCreditCard(function(result) {
if (result.valid) {
const infosuccess = result.card_type == null ? '-' : result.card_type.name
const valid = result.valid
const validlunn = result.luhn_valid
const validlenght = result.length_valid
console.log(infosuccess);
} else {
// $(this)
// const inforeject = result.valid
// console.log(result);
}
});
</script>
<script>
$('#nextaction').click(function(e) {
e.preventDefault();
// my code...
})
</script>
You cannot pass arguments directly in to event handlers. However, there are other approaches you can use.
In this case you can set the 'Next' button to be disabled when the page loads. You can then enable/disable it depending on the result of the credit card validation.
To retrieve the entered card number you can simply read the value from the input when the button is clicked, like this:
const $cardInput = $('#card_number');
const $validateBtn = $('#validate_card');
const $nextBtn = $('#next-action');
$cardInput.validateCreditCard(function(result) {
$nextBtn.prop('disabled', !result.valid); // enable/disable 'next' button
if (result.valid) {
// update the UI to show card details if necessary here...
} else {
console.log('enter a valid credit card number...');
}
});
$nextBtn.on('click', function(e) {
e.preventDefault();
const cardNumber = $cardInput.val();
console.log(cardNumber);
console.log('move to next action here...');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-creditcardvalidator/1.0.0/jquery.creditCardValidator.min.js" integrity="sha512-7omJBgl5QF4QuC3Ge745IO3rDZVMrZWIGK8lSs5lQIFxbWt4d2c7YQg3ZcnonFyRuQslrJ1Ai33Zj/rnXC15+Q==" crossorigin="anonymous"
referrerpolicy="no-referrer"></script>
<p>
Test Card number: 5404000000000084
</p>
<label>
Credit card number:
<input type="text" id="card_number" />
<button type="button" id="validate_card">Validate</button>
</label>
<button type="button" id="next-action" disabled>Next...</button>

JS Validation Function with 3 arguments(//selector,message,validation function for specific input)

I need to implement code which should add eventlistener and on change event check if the form is valid and add the message
let validate = function(element, info, functionValidate) {
let htmlTag = document.querySelector('fieldElem');//?
htmlTag.addEventListener('change',ev=>{
let notif = document.createElement('span');
document.htmlTag.appendChild(notif);//should add span element next to input
if(fieldElem.value == '')
{
notif.style.visibility = "hidden"; //hide span if nothing happens
}
//I need to implement code which should add eventlistener and on change event check if the form is valid and add the message...
Try the following. You could also use form validation (see Form Validation Set Custom Validity for an example)
function validator(val) {
return (val != '');
}
function validateField(element, validator, message) {
var helper = document.createElement("span");
var parent = element.parentElement;
parent.appendChild(helper);
element.addEventListener('change', function() {
var val = element.value;
if (!validator(val)) {
helper.innerText = message;
} else {
helper.innerText = "";
}
});
}
validateField(document.getElementById('test'), validator, 'Wrong input');
<html>
<body>
<form>
<input id="test" type="text" placeholder="Type here"/>
</form>
</body>
</html>

Tried to get data from a form and append it to a global array, but for some reason the data isn't being added

I am trying to get data from a form and append it to a global array but for some reason, the data isn't being added to the array. The code should basically accept the input from the form and store it into the global array. I updated the HTML so you can see the entire syntax. The value should basically be taken from the form and placed into the global array using the "addnew" function.
function addnew()
{
//calculateAge();
//Accept values entered in form
const fname = document.getElementById('fname').value;
const mname = document.getElementById('mname').value;
const lname= document.getElementById('lname').value;
const dob= document.getElementById('dob').value;
const genderM = document.getElementsByName('male').checked;
const genderF = document.getElementsByName('female').checked;
const age = calculateAge.bYear;
const bodyType = document.getElementById('Body Type').value;
const occu= document.getElementById('occu').value;
const height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert();
}
if(mname==null || mname=="")
{
alert();
}
if (lname==null || lname=="")
{
alert();
}
if(dob==null || dob=="")
{
alert();
}
if (genderM.checked == false || genderF.checked == false){
alert();
}
if (age <=18 || age >=75)
{
alert();
}
if(height>=170 || height<=200)
{
alert();
}
if(bodyType==null || bodyType==""){
alert();
}
if(oocu==null || oocu=="")
{
alert();
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(dob);
records.push(genderM);
records.push(genderF);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
//showAll();
//<h1 class="logo"><img src="New folder/logo.jpg" /></h1>
Information.addEventListener('submit', addnew);
}
</script>
```
first of all. name attribute has nothing to do with form element.
second. Information.addEventListener('submit', addnew); has no meaning because Information is not defined.
and to the core. when submiing a form, the page refreshes defaultly, so the addNew function is aborted like all the other variables. in order to prevent it you have to do as follows.
on submit button ad an id attribute:
<button id="submit" type="submit"> Submit </button>
then on top of your JS, get the button element and add an event listener to it:
let submit = document.getElementById('submit');
submit.addEventListener('click', addnew );
and here is the final step. on the addNew function, add an event argument. and on the begining of the function's code, fire the preventDefault method:
function addnew(event) {
event.preventDefault();
// the rest of the code here
}
by the way. you have a typo here. it should be occu.
if (oocu == null || oocu == "") {
alert();
}
good luck!

Javascript validation on select input

I am trying to make a javascript validating form, and am a bit stuck on validating drop down inputs (select)
I have been using this so far but am unsure on how to implement the validation to the select options, if anyone could give me some tips that would be great.
Edit: Also, how would I implement email validation, e.g containing #, thanks
Thanks
<input id="firstname" onblur="validate('firstname')"></input>
Please enter your first name
Thanks
http://jsfiddle.net/ww2grozz/13/
you need to handle select as follow
var validated = {};
function validate(field) {
// Get the value of the input field being submitted
value = document.getElementById(field).value;
// Set the error field tag in the html
errorField = field + 'Error';
// Set the success field
successField = field + 'Success';
if (value != '') {
document.getElementById(successField).style.display = 'block';
document.getElementById(errorField).style.display = 'none';
validated[field] = true;
} else {
document.getElementById(successField).style.display = 'none';
document.getElementById(errorField).style.display = 'block';
validated[field] = false;
}
}
function SimulateSubmit() {
// Query your elements
var inputs = document.getElementsByTagName('input');
// Loop your elements
for (i = 0, len = inputs.length; i < len; i++) {
var name = inputs[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
var all_select = document.getElementsByTagName("select"); // get al select box from the dom to validate
for (i = 0, len = all_select.length; i < len; i++) {
var name = all_select[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
}
here the Working fiddle
using jQuery function
$('input').on('keyup', function() {
var isValid = $.trim($(this).val()) ? true : false;
// show result field is Valid
});
You must use <form> tag and set your action to it I have done that check this link and I have added select tag and set it to -1 by default for checking purpose while validating

How can I extract the values entered in the input boxes generated dynamically and pass it to controller using jquery?

I have a form wherein a user can enter input boxes and remove them at a click. I want to extract the values entered in these input boxes and pass them to controller using jQuery. How do I do that?Right now I am using ids to extract the values but I do not think that is a better method because suppose I add 4 options and then I remove all of them and then again add inputs, I will not be able to track these ids and extract the values.
Here is my HTML code:
<button type="button" class="addoption" id="addoption_btn">Add more option</button>
<div id="Options">
<input type="text" name="mytext[]" id="option_1" placeholder="Option 1"/>
</div>
Here is my JavaScript:
var MaxOptions = 4; //maximum input boxes allowed
var Optionsform = $("#Options"); //Input boxes wrapper ID
var AddButton = $("#addoption_btn"); //Add button ID
var x = Optionsform.length; //initial text box count
var OptionCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxOptions) //max input box allowed
{
OptionCount++; //text box added increment
//add input box
$(Optionsform).append('<div><input type="text" name="mytext[]" id="option_'+ OptionCount +'" placeholder="Option '+ OptionCount +'"/>×</div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
});
Here is the jQuery I am using to pass the data to my controller:
$("#addquestion_btn").click(function(){
var val= CKEDITOR.instances['question_topic'].getData();
storequestion(val);
});
function storequestion(ques)
{
$.post("/instructor/store/question",{
question: ques,
option1: $("#option_1").val(),
option2: $("#option_2").val()
},function(data){
if(data[0]==="success")
{
window.location.href = '/instructor/create/topics';
}
else
{
alert("fails");
window.location.href = '/instructor';
//redirect to further page to enter courses
}}
,'json');
}
Please use below mentioned code to read through all displayed options.
function storequestion(ques) {
obj = {};
obj[question] = ques;
$("#Options:input[name*='mytext']").each(function (index) {
obj['option' + index] = $(this).val();
});
$.post("/instructor/store/question", obj
, function (data) {
if (data[0] === "success") {
window.location.href = '/instructor/create/topics';
}
else {
alert("fails");
window.location.href = '/instructor';
//redirect to further page to enter courses
}
}
, 'json');
}

Categories