User input does not get captured/stored - javascript

I am trying to figure out why this onclick function in my JavaScript and Jquery code are not working.
I am referring my "userInput" in the JavaScript code and storing it in a variable called "userDate". For some reason, the user input does not get captured/stored.
This is my HTML:
<form role="form">
<p> Enter the date:
<input id="userInput" type="text" placeholder="yyyy-mm-dd" autofocus required></p>
<button id="convert" type="submit" class="btn btn-primary btn-lg" padding="center">
<span class="glyphicon glyphicon-euro"></span>
</button>
</form>
This is my JS code:
$(function () {
// cache the DOM element
var $currencies = $("#currencies");
var $userInput = $("#userInput");
// We are listening on the 'document',
// for a click on an element with an ID of #convert in the HTML
$("#convert").on("click", function() {
var userDate = $userInput;
// testing
console.log(userDate);
alert ("Handler for .click() is called.");
// AJAX call for GET request
$.ajax({
type: 'GET',
url: 'http://xxx.xx',
success: function(currencies) {
console.log("success func is called");
console.log(userDate);
$.each(currencies, function(i, currency){
$currencies.append("<div> EUR: " + currencies.rates["EUR"] + ", date: " + currencies.date + "</div>");
});
},
// error handling for my request
error: function() {
alert("error loading currencies");
}
});
});
});

change
var userDate = $userInput;
to
var userDate = $userInput.val();
$userInput is a reference to the jquery object holding the input element. Using .val() returns the text value of that input element.

Related

jQuery validate , how to make validation rules for dynamically generated fields?

I have an HTML form with dynamically add more fields. For example company name. I am trying to use the jQuery validate method to validate. It is working fine with the existing company name field. Here is the code.
<script>
$("#company_creation_form").validate({
rules:{
company_name: {
required: true,
minlength: 3
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize()+"&company_count="+company_count,
success: function () {
alert("thanks");
}
});
return false; // required to block normal submit since you used ajax
}
});
</script>
When I click on add more button another company name field will create on the form. The below code is failed to validate the dynamically generated field. Here I am getting the field count globally in this variable company_count
<script>
$("#company_creation_form").validate({
rules:{
company_name: {
required: true,
minlength: 3
},
I tried like below, but this is giving me error
if(company_count> 0){
var new_field = jQuery("#company_name"+company_count);
new_field : {
required: true,
minlength: 3
},
}
The above block code is showing error in the text editor it self
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize()+"&company_count="+company_count,
success: function () {
alert("thanks");
}
});
return false; // required to block normal submit since you used ajax
}
});
</script>
Can anyone help me with how to make validation for these dynamically generated fields? Any help would be greatly appreciated. I am using form submission by using Ajax.
Code to add company fields dynamically
var company_room = 0;
var company_room1 = 0;
function add_another_company() {
company_room++;
company_room1++;
var objTo = document.getElementById('company_field')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass2" + company_room);
//var rdiv = 'removeclass2' + company_room;
divtest.innerHTML = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="company_name" name="company_name" placeholder="Company Name"></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button" onclick="remove_another_company(' + company_room + ');"> <i class="fa fa-minus"></i> </button> </div></div></div>';
objTo.appendChild(divtest);
var E_fields = $('.aj4');
var E_count = 1;
$.each(E_fields, function() {
jQuery(this).attr('id','company_name' + E_count);
jQuery(this).attr('name','company_name' + E_count);
E_count++;
});
}
function remove_another_company(rid2) {
company_room1--;
$('.removeclass2' + rid2).remove();
var E_fields = $('.aj4');
var E_count = 1;
$.each(E_fields, function() {
jQuery(this).attr('id','company_name' + E_count);
jQuery(this).attr('name','company_name' + E_count);
E_count++;
});
}
OK, so I didn't have your HTML so I had to mock some up. You will obviously have to tweak this a little to work with your ID's. I tried to keep it as close as possible to the ID's/classes you were already using.
I removed the pure javascript functions and the onclick events in favor of jquery since you were already using it. Hopefully this kind of simplifies things a bit and makes it more manageable.
NOTE: I added a hidden input field to keep track of company count. This way it will be included when you $(form).serialize in your ajax options (as you are adding it with a variable now). I included code to preserve the company_count variable also, so basically you will have 2 company counts. I did this just to show you an easier way to keep track of this without having to micro manage it. :)
Try out this code and let me know what your getting in console if it is not working. Thanks
MOCK HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form-wrapper">
<p>Dynamic Form</p>
<button id="addField">Add Dynamic Field</button>
<form id="dynForm">
Static Field: <input id="company_name" name="company_name" minlength="3" type="text" value="Static Company Name" required>
<br>
<input type="hidden" id="companyCount" name="companyCount" value="1">
<div id="company_field">
</div>
</form>
</div>
JQUERY/JS
$(function() { // <---- Document Ready!
$("#addField").on("click", () => {
var count = parseInt($("#companyCount").val(), 10);
count += 1;
$("#companyCount").val(count.toString());
var thisId = "company_name" + count.toString();
var html = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="'+thisId+'" name="'+thisId+'" minlength="3" placeholder="Company Name" required></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button"> <i class="fa fa-minus"></i> </button> </div></div></div>';
var ele = $.parseHTML(html);
$("#company_field").append(ele);
});
$("#company_field").on("click", "button", () => $(this).closest(".form-row").remove());
$("#company_creation_form").validate({
submitHandler: function(form) {
var company_count = parseInt($("#companyCount").val(), 10);
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize() + "&company_count=" + company_count,
success: function() {
alert("thanks");
}
});
return false;
}
});
});

How to send POST requests from dynamic fields?

I'm creating a quiz form to pass into a JSON file, but I'm having trouble sending the POST requests. I'm not sure which fields I can access, or how.
This is the form: https://i.imgur.com/6xtmt3a.png
<script>
// input field
$(document).ready(function() {
var wrapper = $(".div1");
var newbutton = $(".add_form_field");
var fields = 1;
$(newbutton).click(function(e) {
e.preventDefault();
$(wrapper).append(' <div class="input-group"> <input type="text" value = "Question" class="form-control" placeholder="Recipients username" <div class="input-group-append" id="button-addon4"><button class="btn btn-outline-secondary" id ="delete" type="button">Delete</button><button class="btn btn-outline-secondary" id ="add" type="button">Add</button></div></div></div>'); //add input box
//$(wrapper).append('<button type="button" id ="test1" class="btn btn-primary">Primary</button>'); //add input box
//$(wrapper).append('<div><input type="text" value = "Question"name="mytext[]"/> Delete add </div> '); //add input box
var d = $(this).parent('form').serialize();
console.log(d);
});
//delete buttons
$(wrapper).on("click", "#delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
fields--;
})
// remove div
$(wrapper).on("click", '#s1', function(e) {
//$(this).parent('div').parent('div').remove();
var q= $(this).parent().serialize();
console.log(q);
})
//add answer
$(wrapper).on("click", "#add", function(e) {
e.preventDefault();
$(this).parent('div').append('\n <div class="input-group flex-nowrap"><div class="input-group-prepend"><span class="input-group-text" id="addon-wrapping">-</span></div><input type="text" class="form-control" placeholder="Answer" aria-label="Username" aria-describedby="addon-wrapping"></div> ' );
var d = $(this).parent('form').serialize();
console.log(d);
//$(this).parent('div').parent('div').append('<div class="input-group mb-3"><input type="text" class="form-control" placeholder="Recipients username" aria-label="Recipients username" aria-describedby="button-addon2"><div class="input-group-append"><button class="btn btn-outline-secondary" type="button" id="button-addon2">Button</button></div></div>' );
fields--;
})
});
$( "#quizForm" ).submit(function( event ) {
var $form = $( this ),
path = $form.attr( "action" );
payload = {"testKey":"test"};
var posting = $.ajax({
url: path,
method: "POST",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: payload,
dataType: "application-json",
});
console.log(payload);
posting.done(function() {
console.log("posted");
});
});
</script>
I need to have a JSON file output on submit that contains the questions and answers to each question (right or wrong for now) Thanks!
I would suggest adding an attribute contains the object's key on each question - let's say it will be the "question ID".
we will have something like that:
<div class="question-container" question-id="01"></div>
Assuming that answers are an .answer div with an input inside we will have something like that on form submit:
let formObject = new Object();
$('.question-container')
.each(function () {
const questionID = this.attr('question-id');
const answersArray = new Array();
this.find('.answer input')
.each(function () { // assuming answer is a div contains an input tag
answersArray.push(this.value());
})
formObject[questionID] = answersArray;
})
/// here formObject contains the formatted form as json

Submitting 2 forms separately via AJAX - Python Flask

I'm trying to submit 2 separate forms via AJAX, but on submitting form2 I get a 500 bad request error.
My HTML code is below, but basically my page is a flask template that works as follows:
*User makes selections
*These selections are then posted via the submit button named "button" Value "Calculate Available Overall Heights".
*This runs some SQL query to determine a list of entries that are placed into a newly generated <select id="mySelect" class="form-control" onchange="myFunction()"></select>
This is done by JS which is also listed below as MyJS.js
OAH.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p class="h2">XXX</p>
<form method="post" id="form1">
<fieldset>
</div>
<div class="col-sm-3">
<span style="float:left"><label>Overall Height</label></span>
///my inputs, various selects etc ///
<div id="response">
<!-- Empty element until form submitted-->
</div>
<p id="ApertureHeight"></p>
<p id="ApertureHeightBelowPelmet"></p>
<p id="ApertureHeightUnderRoofSticks"></p><br>
<p id="OverallWidth"></p>
<p id="RearAppWidth"></p>
<p id="RearPillarNS"></p>
<p id="OAH"></p>
</div>
</fieldset>
<script src="/static/js/MyJS.js"></script>
</form>
<form method="post" id="form2">
<div class="col-sm-3">
<label>
<span style="float:left"><input type="text" id="myText" value=""></span>
</label>
<br>
<input type="button" value="Click Me!" onclick="submitForms()" />
</div>
</form>
</body>
</html>
form2 has a button called "Click Me!" which calls a function that submits form 2.
submitForms = function(){
document.getElementById("form2").submit();
};
MyJS.js
$("#form1").on("submit", function(event) {
$targetElement = $('#response');
event.preventDefault();
// Perform ajax call
//
console.log("Sending data: " + $(this).serialize());
$.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call
})
});
submitForms = function(){
document.getElementById("form2").submit();
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$("#form2").on("submit", function(event) {
event.preventDefault();
console.log("Sending data: " + $(this).serialize());
$.ajax({
url: '/OAH',
data: $('#form2').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call
})
});
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function myFunction() {
var FifthWheel = document.getElementById("FifthWheelHeight").value;
var NeckDepth = document.getElementById("NeckDepth").value;
var CantRailDepth = document.getElementById("CantRailDepth").value;
var RearTensioner = document.getElementById("RearTensioner").value;
var OAH = document.getElementById("mySelect").value;
if (CantRailDepth = 115) {
var PelmetDim = 100;
} else {
PelmetDim = 75;
}
var ApertureHeight = Number(OAH) - Number(FifthWheel) - Number(NeckDepth) - Number(CantRailDepth);
var ApertureHeightBelowPelment = Number(ApertureHeight) - Number(PelmetDim);
var ApertureHeightUnderRoofSticks = Number(OAH) - Number(FifthWheel) - Number(NeckDepth) - 35;
document.getElementById("ApertureHeight").innerHTML = "Aperture below Cantrail = " + ApertureHeight + "mm";
document.getElementById("ApertureHeightBelowPelmet").innerHTML = "Aperture below pelmet = " +
ApertureHeightBelowPelment + "mm";
document.getElementById("ApertureHeightUnderRoofSticks").innerHTML = "Aperture below roof sticks = " +
ApertureHeightUnderRoofSticks + "mm";
document.getElementById("OverallWidth").innerHTML = "Overall Width = 2548mm (2550mm on spec)";
document.getElementById("OAH").innerHTML = OAH;
document.getElementById("myText").value = document.getElementById("OAH").innerHTML;
}
I need this form to submit separately, via AJAX without refreshing the page, as I need the JSON array to be able to calculate further stuff that will be passed into Python Flask. My issue is I am getting a bad request when submitting form2.
Anyone got any ideas on what I have done wrong?
I think you are using the same endpoint URL to try handle 2 different requests. The 2nd form does not send the correct data and you're then getting Server errors. Try creating another endpoint on your python flask server for handling form2 and the myText field value.

Clear input and start chat scroll from bottom

I'm trying to clear the input on a message submit. And also on chat window load keep the scroll at the bottom.
I've tried many scripts, I've also tried different approaches, outsourcing. But I think due to my structure something just isn't right. I will admit I'm no expert when it comes to anything JavaScript related. I'm just dying to get this done out the way, its been bugging me for months now that I cannot get it to work.
Here is my code
var scrolled = false;
function updateScroll() {
if (!scrolled) {
var element = document.getElementById("ChatPopScroll");
element.scrollTop = element.scrollHeight;
}
}
$("#ChatPopScroll").on('scroll', function() {
scrolled = true;
});
$(function() {
$('form#SendForm').on('submit', function(e) {
$.post('elements/sendmessagefriend.php', $(this).serialize(), function(data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
$('#message').val('');
var form = document.getElementById("SendForm");
form.reset();
$('#SendForm').trigger("reset");
})
.error(function() {
$('#message').val('');
});
e.preventDefault();
$('#message').val('');
});
});
$(document).ready(function() {
$('div.message-window').each(function(index, messageWindow) {
messageWindow = $(messageWindow);
// Run fetchMessages() once, when the page is loaded.
fetchMessages(messageWindow);
// Set an interval timer for checking messages.
// Not ideal, but it works for now.
setInterval(fetchMessages, 500, messageWindow);
// in milliseconds!!!!!! (1000ms = 1s)
});
});
function fetchMessages(messageWindow) {
// For each message window, check for new chats
// Get the friend_id from the window
var friend_id = messageWindow.attr("friend_id");
// Get the last chat message_id from the last chat message in this window.
var last_message_id = messageWindow.find("ul > li:last").attr("message_id");
// Ask the server for the latest messages.
// Send over the friend_id and last_message_id, so it can send back new messages from this friend.
$.get("elements/chat-load.php", {
last_message_id: last_message_id,
friend_id: friend_id
}, function(messages) {
// This function is run when the AJAX request succeeds.
// Append the new messages to the end of the chat
messageWindow.find("ul").append(messages);
});
}
function openPopup(ID) {
$('.popup');
$("#" + ID).fadeIn(200);
}
function closePopup(ID) {
$('.popup');
$("#" + ID).fadeOut(200);
}
function MinPopup(ID) {
$('.popup');
$("#" + ID).addClass('ChatMinPop').removeClass('ChatActivePop');
}
function UpPopup(ID) {
$('.popup');
$("#" + ID).addClass('ChatActivePop').removeClass('ChatMinPop');
}
<div id="ChatPopScroll" class="ChatPopMsg">
<div id="messages" class="messages message-window" friend_id="<?=$FriendName->id ?>">
<ul id="ScrollAuto" class="message">
</ul>
</div>
</div>
<div class="ChatPopFoot">
<form autocomplete="off" id="SendForm" class="SendMsg" role="form" method="post">
<input autocomplete="off" id="message" class="ChatPopFootTxt" type="text" name="message">
<input style="" id="submit" class="submit MsgInputHidden" type="submit" name="submit" value="Submit" />
</form>
</div>

Passing form's input to Parse.com

I am playing around a bit with Parse.com and I am trying to send HTML form's content to Parse.com
I am kind of a Javascript noob so for some reason I cannot find a way to pass a variable I got from the form's input to Parse.com for processing.
Here's my code:
<div class="main">
<form action="">
<label>Insert your ingridient :</label>
<input type="text" id="text" name="name" value="" />
<input type="button" id="text_value" value="Get Value"/>
<script type="text/javascript">
$(document).ready(function() {
$('#text_value').click(function() {
var text_value = $("#text").val();{
alert(text_value);
}
});
});
Parse.initialize("myAPIKey", "myAPIKey");
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
name: text_value,
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
}
});
</script>
You should wrap the code that does the saving inside a function, then call it when the user clicks the button. You have a few errors with your {} brackets as well. Indenting your code when writing it will help you avoid that.
<div class="main">
<form action="">
<label>Insert your ingridient :</label>
<input type="text" id="text" name="name" value="" />
<input type="button" id="text_value" value="Get Value"/>
<script type="text/javascript">
$(document).ready(function() {
$('#text_value').click(function() {
var text_value = $("#text").val();
save(text_value);
});
Parse.initialize("myAPIKey", "myAPIKey");
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
function save(value) {
gameScore.save({name: text_value}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
}
});
};
};
</script>

Categories