Using jQuery to Populate Data from More Than One Select Control - javascript

Anytime a person gets executed, I notify the Judge who put him away.
Recently, we have found there is a problem with people putting down the wrong Executioner. This would not normally be a big deal, but there are some bosses with big families that can make life difficult for the person that performed the execution.
So, the form now needs to be modified to also include an email to the Executioner.
Here are the basics of the webpage:
<form method="post">
Person Executed:
<input type="text" name="_jp2code_killed" value="" size="30" />
<br />
<input type="hidden" name="_jp2code_name_original_value" id="_jp2code_name_original_value" value="Web Master" />
<input type="hidden" name="_jp2code_mail_original_value" id="_jp2code_mail_original_value" value="no-reply#jp2code.net" /><br />
Judge:
<select name="Judge" id="Judge">
<option value="Neal Barton" _jp2code_judge="NBarton#ketknbc.com">Neal Barton</option>
<option value="Howard Pain" _jp2code_judge="hpain#courtcircuit1.us">Howard Pain</option>
</select>
Executioner:
<select name="Executioner" id="Executioner">
<option value="Joe Byrd" _jp2code_executioner="jbyrd#walls.tx.us">Joe Byrd</option>
<option value="Jim Estelle" _jp2code_executioner="jestelle#tdcj.org">Jim Estelle</option>
</select>
<br />
<input type="submit" value="Submit" />
<br />
debug:
<input type="text" name="_jp2code_debug" id="_jp2code_debug" size="30" /><br />
</form>
With those definitions in place, here is the jQuery (v1.7) that I am trying to get to work:
$(function () {
// Save references to elements
var objName = $('#_jp2code_name_original_value');
if (!objName.attr('_jp2code_custom_parameter') ||
($.trim(objName.attr('_jp2code_custom_parameter')) == '')) {
objName.attr('_jp2code_custom_parameter', objName.val());
}
var objEmail = $('#_jp2code_mail_original_value');
if (!objEmail.attr('_jp2code_custom_parameter') ||
($.trim(objEmail.attr('_jp2code_custom_parameter')) == '')) {
objEmail.attr('_jp2code_custom_parameter', objEmail.val());
}
$('#Judge').each(function () {
$(this).change(function () { // Add OnChange EventHandler
var oItem = $(this); // reference to current element
var oName = $('#_jp2code_name_original_value'); // Save references to names
var oEmal = $('#_jp2code_mail_original_value'); // Save references to emails
if ($.trim(oItem.Val()) != '') {
oName.val(oName.attr('_jp2code_mail_original_value') + ',Judge');
oEmal.val(oEmal.attr('_jp2code_mail_original_value') + ',' + $(this).children(':selected').attr('_jp2code_judge'));
} else {
oName.val(oName.attr('_jp2code_mail_original_value'));
oEmal.val(oEmal.attr('_jp2code_mail_original_value'));
}
$('#_jp2code_debug_name').val(oName.val());
$('#_jp2code_debug_emal').val(oEmal.val());
});
});
});
So, despite my best efforts, a couple of things aren't working:
My debug boxes that should be getting the people's names and email addresses is not working. Those debug boxes should always at least include the Web Master name and email address, then append the person's name and address when they are selected. I can't seem to get past that.
Once that is working, how would I add the logic functioning, then I need to include both names and both email addresses from the select boxes.
Here is where I have been fiddling with this:
http://jsfiddle.net/jp2code/c5Q2V/

I solved it.
JS Fiddle: http://jsfiddle.net/jp2code/wunC2/1/
I added a custom attribute to my elements with "Web Master" or the default email address to the HTML:
<form method="post">
Person Executed: <input type="text" name="_jp2code_killed" value="" size="30"/>
<br/>
<input type="hidden" name="_jp2code_name_original_value" id="_jp2code_name_original_value" _jp2code_name_original_value="Web Master" />
<input type="hidden" name="_jp2code_mail_original_value" id="_jp2code_mail_original_value" _jp2code_mail_original_value="norsvp#mail.com" /><br/>
Judge:
<select name="Judge" id="Judge">
<option value="First1 Judge1" _jp2code_judge="judge1#mail.com">First1 Judge1</option>
<option value="First2 Judge2" _jp2code_judge="judge2#mail.com">First2 Judge2</option>
</select>
Executioner:
<select name="Executioner" id="Executioner">
<option value="First1 Exec1" _jp2code_executioner="exec1#mail.com">First1 Exec1</option>
<option value="First2 Exec2" _jp2code_executioner="exec2#mail.com">First2 Exec2</option>
</select>
<br/>
<input type="submit" value="Submit" />
<br/>
debug: <input type="text" name="_jp2code_debug_name" id="_jp2code_debug_name" size="50" /><br/>
debug: <input type="text" name="_jp2code_debug_emal" id="_jp2code_debug_emal" size="50" /><br/>
</form>
For the jQuery, I trimmed it down to a function that was passed to both Select controls, and I had to call the function once so the data would be pre-populated:
$(function() {
function jp2code_get_data() {
var obj1 = $('#_jp2code_name_original_value');
var val1 = obj1.attr('_jp2code_name_original_value');
val1 += ','+$('#Judge').children(':selected').val();
val1 += ','+$('#Executioner').children(':selected').val();
var obj2 = $('#_jp2code_mail_original_value');
var val2 = obj2.attr('_jp2code_mail_original_value');
val2 += ','+$('#Judge').children(':selected').attr('_jp2code_judge');
val2 += ','+$('#Executioner').children(':selected').attr('_jp2code_executioner');
obj1.val(val1);
obj2.val(val2);
$('#_jp2code_debug_name').val(obj1.val());
$('#_jp2code_debug_emal').val(obj2.val());
}
$('#Judge, #Executioner').each(function () {
$(this).change(jp2code_get_data);
});
jp2code_get_data();
});
This is probably not helpful to everyone, but I like to post the solution if others have the same problem.

Related

HTML - Input DataList - Check Value is in the List

I want to check if the Value enter in the input is in the datalist.
If not i inform that the value is not in the list, I write something but the submit is done anyway, i miss something ?
Edit: I edit to have a trial form. If i enter productD the submit can't not be done becuase is not in the list defined.
<tbody>
<div class="fichetechniquediv">
<form action="{% url 'createdfichetechnique' %}" method='post' onclick="return myCheckFunction(this)">
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlist" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="productA">productA</option>
<option value="productB">productB</option>
<option value="productC">productC</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
</div>
</tbody>
<script>
function myCheckFunction(form) {
var list = document.getElementsById("productslist");// get the values that are currently under the datalist tag in option tags
var val = document.getElementsByName("Product");// get the user input
if( list.include(val)){ // compare the options with the user input
submit(form)}// if one is equal with the user input submit the form with the method submit();
else{
return false// else don't submit the form, the user will have to change his input
}
}
</script>
Example productD
const list = document.querySelector("#productslist")
const btn = document.querySelector(".buttonsave")
console.log(list.options.length)
if(list.options.length <= 0 ){
btn.disabled = true
}else {
btn.disabled = false
}
Check if is any products. If the script can't see any products disable the button to send. I hope I helped
You cannot use include for DOM elements like you do.
Also you have duplicate IDs
Instead do this:
const list = document.querySelectorAll("productslist option")
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = document.getElementById("productlistInput").value
const found = [...list].find(opt => opt.value===val)
if (!found) {
alert("Please choose an existing value");
e.preventDefault();
}
})
<form id="myForm" action="..." method='post'>
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlistInput" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="prod1">Product 1</option>
<option value="prod2">Product 2</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
There are two things going wrong in this:
document.getElementsById("productslist"); is incorrect. The function is getElementById(...)
document.getElementById("productslist"); will get you an HTML nodes, not the values.
One of the ways to get the values is:
const values = [];
Array
.from(document.getElementById("productslist").options)
.forEach((option) => {
values.push(option.value);
}
Now that you have the values in the values array, you can look it up to check if the value is already present.

How to make html <input> tag with pre-written data

I'm working on a project, and for testing it I need to fill in a large amount of 'input' elements every time when reloading the page. I'm filling in the same numbers every time, so I need 'input' elements to somehow 'remember' the value they were given.
I've seen an example with 'autocomplete' attribute, but then I have to choose the value from a drop box for each input element, so that won't help me.
Is there any way I can code the input tag with pre-written data? Or maybe using javascript?
With jQuery, you can write a plugin to set the input of fields based on data.
You can do the same without jQuery, but you need to find all inputs, textareas, selects, etc. and filter the other junk out of the form before setting values.
Check out this question for more tips: Using jQuery and JSON to populate forms?
(function($) {
$.fn.populateData = function(data) {
var $form = this;
$.each(data, function(key, value) {
$('[name=' + key + ']', $form).val(value);
});
}
})(jQuery);
var pocForm = document.forms['poc-form'];
var pocFormData = {
fname : 'John',
lname : 'Doe',
dob : '1970-12-25'
};
$(pocForm).populateData(pocFormData);
.form-field {
margin-bottom: 0.25em;
}
.form-field label {
display: inline-block;
width: 6em;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="poc-form">
<div class="form-field">
<label for="poc-fname">First Name:</label>
<input type="text" id="poc-fname" name="fname" />
</div>
<div class="form-field">
<label for="poc-lname">Last Name:</label>
<input type="text" id="poc-lname" name="lname" />
</div>
<div class="form-field">
<label for="poc-dob">Date of Birth:</label>
<input type="date" id="poc-dob" name="dob" />
</div>
</form>
here the unput value
<form >
First name: <input type="text" name="fname" value="John"><br>
Last name: <input type="text" name="lname" value="Doe"><br>
</form>
In your input you can use the value tag and set the default value.
<input type="text" name="example" value="Value Goes Here">
You can more or less tell autocomplete how to work: https://html.spec.whatwg.org/multipage/forms.html#autofill
But it still leaves it up to the browser.
A better option is datelist, giving you a text-input with predefined options for autocomplete and an dropdown-menu.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist
<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" />
</label>
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
<option value="Microsoft Edge">
</datalist>
EDIT:
After reading your question again, I realized that this isn't very good for your use-case. Sorry.
In that case I'd just go with a single line of jQuery:
$('input[type="text"]').val('Hello world') ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="t1" />
<input type="text" name="t2" />
<input type="text" name="t3" />
<input type="text" name="t4" />
<input type="text" name="t5" />
<input type="text" name="t6" />
<input type="text" name="t7" />
with Javascript, you can use static text in strings:
var mystring = "This is my string of text";
var anotherString = "A second string of text";
var myInputs = document.getElementsByTagName("input");
myInputs[0].value = mystring;
myInputs[1].value = anotherString;
If you need the text to be from user entered data, you need to first save the text:
tx = myInputs[0].value
localStorage.setItem("item_name", tx);
//note: you would need to use a keyup event or button to save the data as the user types or clicks the button. Also look in to JSON "stringify" and "parse" to save more complex items.
After you have saved the data you wished, call it and point it to the input you wish.
var savedTx = localStorage.getItem("item_name");
if (savedTx) {//it's important to look for the data first to avoid errors
myInputs[0].value = "My data: " + savedTx + "!";
}

how do I correctly pass a JavaScript value that has been adjusted via if...else back into my web-page before it is submitted to my payment portal?

I have an online payment form which my clients can use to pay me via a hosted payment portal. If a client pays by debit-card there is no additional fee incurred. However, if a client pays via credit-card they are charged an additional 2.5% admin fee. I have created a basic form which follows the same structure and have used pop-ups to show that they correct value is held. The problem that I am having is that when I then try and pass that value to the payment-portal I am given a 'Fault 8' code. I have tried to resolve the problem with the provider of the payment solution but they have been less than helpful and I am not keen to upgrade to their 'premium plan' and another 12 months of trouble.
The basic form is:
<HTML> <HEAD> <TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function cardHandlingFee (form) { var Notes = form.Notes.value; var amountPaid = form.amountPaid.value; var clientname = form.clientname.value; var CustomerEmail = form.CustomerEmail.value; var percent = 0.025; var CreditCardCharge; var totalCharge;
if ( Notes == "Debit Card" ) { TransactionAmount = amountPaid; alert ("You typed: " + TransactionAmount); } else { CreditCardCharge = amountPaid * percent; totalCharge = parseFloat(amountPaid) + parseFloat(CreditCardCharge); TransactionAmount = totalCharge.toFixed(2); alert ("You typed: " + TransactionAmount); } }
</SCRIPT> </HEAD> <BODY>
<form id="contactform" action="https://(PAYMENT-SOLUTION DETAILS)" method="POST" name="confirm">Enter something in the box: <BR> <p class="padding:2px"> <select id="CardType" name="Notes" required> <option value="Credit Card">Credit Card</option> <option value="Debit Card">Debit Card</option> </select></p>
<p class="padding:2px"><input id="amountPaid" type="number" name="amountPaid" min="0" max="9999" step="0.01" size="4" /> <script type='text/javascript'>
quote = 'This is the quote of the day!';
document.contactForm.TransactionAmount.value = TransactionAmount;
alert(document.contactForm.TransactionAmount.value);
</script>
<p class="padding:2px">Clients full name*<br /><input type="text" name="clientname" value="" /></p>
<p class="padding:2px">Your email address*<br /><input type="email" name="CustomerEmail" value="" /></p>
<input type="submit" onClick="cardHandlingFee(this.form);" value="Submit Card" />
<input type="hidden" name="CustomerID" value="(CLIENT CUS ID)" /> <input type="hidden" id="TransactionAmount" name="TransactionAmount" /> <input type="hidden" name="TransactionCurrency" value="826" /> <input type="hidden" name="RedirectorSuccess" value="http://(CLIENT SITE)/success" /> <input type="hidden" name="RedirectorFailed" value="http://(CLIENT SITE/failed" /> </FORM>
</BODY> </HTML>
I would greatly appreciate any help in either solving the problem with this or another method. This is within my WordPress site. I have tried Jquery, Jscript, .innerHTML but I am now stumped.
As far as I can tell, you're nearly there. You just need to add the following line immediately after the if(){...} else{...} structure :
form.TransactionAmount.value = TransactionAmount;
One other thing, as form.Notes is a select menu, form.Notes.value will only work in some browsers. You should make the following change.
//var Notes = form.Notes.value;
var Notes = form.Notes[form.Notes.selectedIndex].value;

how to set form value with external select value

so i am using the play framework and I'm try to create multiple submit buttons that call the one form:
So what I have is a list of strings, and i would like to create two buttons that will go back to the server and complete an event, the first is send the second is cancel. What i would like to also do is set the source value equal to what is selected in the foo select object. How would I go about doing this? Do i need to create a javascript even that is fired from the form and then get the var inside that function and then fire off the submit? Im not 100% familiar with play framework and scala, so im not sure if i can get it somehow inside this code without using a new method.
#(myList: List[String], theForm: Form[Obj])
#import helper._
#main("myVar Controller") {
<select id="foo">
</select>
<table border="1">
<tr>
#for(myVar <- myList) {
<td>#myVar
#form(routes.Application.method()) {
<div id="hiddenForm" style="visibility:hidden">
<input type="text" name="commandID" id="commandID" value="10" /> //Send Code
<input type="text" name="source" id="source" value=**"Put selected value of foo here" />**
<input type="text" name="destination" id="destination" value="#myVar" />
</div>
<input type="submit" value="Send" />
}
#form(routes.Application.method()) {
<div id="hiddenForm" style="visibility:hidden">
<input type="text" name="commandID" id="commandID" value="18" /> //Undo code
<input type="text" name="source" id="source" value=**"Put selected value of foo here" />**
<input type="text" name="destination" id="destination" value="#myVar" />
</div>
<input type="submit" value="Undo" />
}
</td>
}
</tr>
</table>
}
First of all, the html isn't valid.
You should first make sure that there aren't elements that have the same id.
You have to use javascript to change a value in your form.
I'm not familiar with scalar or playframework, but if they allow you to use jQuery, I recommend the following solution.
$("#foo").bind("change", function(){$("#source").val($("#foo").val()));});​
example:
http://jsfiddle.net/RubenJonker/a8a8p/5
If they don't allow you to use jQuery, then you should put some javascript in the onchange event of the select.
<select onchange="document.getElementById('source').value = this.value">
</select>
example:
http://jsfiddle.net/RubenJonker/a8a8p/4
Incase anyone else has this problem I used the following to solve my problem: Thanks Ruup as your code was the reason why I solved the problem
html:
<select id="foo" >
<option></option>
<option value="test">test</option>
</select>
<input type="text" value="" name="field" id="field" />​
and javascript:
$(document).ready(function() {
obj = document.getElementById("foo");
obj.onchange = function()
{
var elements = document.getElementsByName('field');
for (i=0;i<elements.length;i++)
{
elements[i].value = $('#foo').val();
}
}; });

TypeError: object is not a function, when it is!

I am having trouble with some Ajax functionality.
I have a single dropdown that needs to update a record when the option changes. Here is a snippet of the Javascript:
function changeResponsibleParty(selectObj, targetDiv){
var idx = selectObj.selectedIndex;
var which = selectObj.options[idx].value;
target = document.getElementById(targetDiv);
target.value = which;
document.forms["changeResponsibleParty"].submit();
}
And the HTML:
<form name="changeResponsibleParty" action="javascript:changeResponsiblePartyAjax('project_todos');" method="post" style="display:inline;">
<input type="hidden" name="todo_id" id="todo_id_15" value="15" />
<input type="hidden" name="project_id" id="project_id_15" value="2" />
<input type="hidden" name="user_id" id="user_id_15" value="" />
<select name="user_id_pick" id="user_id_pick_15" onchange="changeResponsibleParty(this, 'user_id_15');" style="border:0;">
<option value="0">Anyone</option>
<option value="1" selected="selected">Allen McCabe</option>
<option value="2">Thomas Martinez</option>
</select>
</form>
I am using the function to update a hidden input element because for some reason, the tag was posting 1 regardless of which option I chose (1 is my user_id, which I set as selected if the database record value is 1.
Can anyone see what is wrong here?
You use changeResponsibleParty as name for the form and also as name for the function, which will cause conflicts. Rename one of them.

Categories