populate a HTML select in form using Javascript - javascript

I have a problem by populating a HTML select.
This select is in an form that first is loaded into a div. (see the code below)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" />
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function createForm(){
$("#formdiv").load("Register.html");
var itemval= '<option value="OT">OT</option>';
document.getElementById("sel").appendChild(itemval);
}
function validateForm(){
// ...
}
</script>
</head>
<body onload="createForm()">
<div id="formdiv" >
// here will be the form
</div>
</body>
The Register.html is a simple form
<h2>Register</h2>
<form name="registerForm" id="registerForm" onsubmit="validateForm()">
Select:<select name="sel" id="sel"></select>
<input type="submit" value="Submit">
</form>
The function createForm() should populate, here as a first test, the select tags. But unfortunately it does not show any option in the browser.
Hope some of you are more experienced than I and can hint me to the solution.
Thanks in advance!

Here the problem is that you use appendChild with a String,
you should use innerHTML to insert a string, or of you want to append
do createElement and then append, appendChild accepts Node as a parameter,
in your case its better use add() method on select
http://www.w3schools.com/jsref/met_select_add.asp
<script type="text/javascript">
function createForm() {
var option = document.createElement("option");
option.text = "OT";
option.value = "OT";
document.getElementById("sel").add(option);
}
function validateForm() {
// ...
}
</script>
<div id="formdiv">
<form name="registerForm" id="registerForm" onsubmit="validateForm()">
Select:
<select name="sel" id="sel"></select>
<input type="submit" value="Submit">
</form>
</div>
<h2>Register</h2>
See jsfiffle link: http://jsfiddle.net/qgfbhgwd/
with a working example

You have 2 mistakes:
Use jQuery load function because is async so you are creating the content before loading the file register.html
appendChild needs a DOM Element instead of a string
This code fix your problem, hope it helps:
function createForm(){
var populateSelect = function() {
var itemsValues = ['OT', 'FOO', 'BAR'];
var items = document.createDocumentFragment();
itemsValues.forEach(function(el) {
var option = document.createElement("option");
option.value = el;
option.innerHTML = el;
items.appendChild(option);
});
document.getElementById("sel").appendChild(items);
};
$("#formdiv").load("register.html", populateSelect);
}

You can't add <option value="OT">OT</option> directly as appendChild, so use javascript createElement and always better to write a callback function for jquery load() to manipulate DOM.
function createForm() {
$("#formdiv").load("Register.html", function () {
//var itemval = '<option value="OT">OT</option>';
var itemval = document.createElement("option");
itemval.setAttribute("value", "OT");
itemval.innerText = "OT";
document.getElementById("sel").appendChild(itemval);
});
}

Related

Dynamically Add and Remove HTML Elements not working

I need to dynamically add and remove HTML elements to my product form (attribute addition purpose) and was searching stack overflow.
I found this solution to be very close (except it does not has a remove option plus I sincerely do not know how to retrieve the data of each textbox, but all this later).
https://jsfiddle.net/nzYAW/
The code in the fiddle works fine. But as I tried it on my local machine it fails to produce any result.
Here is what I did
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.extraPersonTemplate {display:none;}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function () {
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).hide().appendTo('#container').slideDown('slow');
});
})
function GetHtml() {
var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
$html.find('[name=firstname]')[0].name = "firstname" + len;
$html.find('[name=lastname]')[0].name = "lastname" + len;
$html.find('[name=gender]')[0].name = "gender" + len;
return $html.html();
}
</script>
</head>
<body>
<div class="extraPersonTemplate">
<div class="controls controls-row">
<input class="span3" placeholder="First Name" type="text" name="firstname">
<input class="span3" placeholder="Last Name" type="text" name="lastname">
<select class="span2" name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div>
<div id="container"></div>
<i class="icon-plus-sign icon-white"></i> Add another family member</p>
</body>
</html>
and this is the result
Where did I go wrong at copy paste?
You need to load jQuery library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to include jQuery. If you check your javascript console (which you definetly should) you will probably find this error:
$ is not defined
That is because jQuery wasn't loaded before you try to use it. Add this to your page before your javascript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can see in the JSFiddle that you include these libraries, but you don't include them when you just copy paste this.
Include these javascripts
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
Move the JavaScript to be right above the </body> tag.
I think if you're trying to access elements before the page has loaded them, then it won't work.
Also as other answers have pointed out, be sure you've included jQuery in the <head></head> section of your page.

I can't do a submit with jquery

This is my page:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="/Scripts/jquery-2.1.3.js"></script>
<script>
function DoSubmit() {
if ($("#noAggLabel")) {
$("#noAggLabel").innerHTML = "";
}
if (this.value) {
$("#orderForm").submit();
}
}
</script>
</head>
<body>
<div>
<form action="/Orders/GetXML" id="orderForm" method="post"> <p>
<select id="OrdersSelect" name="productionOrderId" onchange="DoSubmit();"><option value="">Orders</option>
<option value="1">Order 1</option>
<option value="2">Order 2</option>
<option value="3">Order 3</option>
</select>
</p>
</form> </div>
<div id="codesTable">
</div>
</body>
</html>
I'm developing a ASP.NET MVC 5 app with .NET Framework 4.5.1 and C#.
This is the View that generates that HTML:
#model Models.ProductionOrderViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script>
function DoSubmit() {
if ($("#noAggLabel")) {
$("#noAggLabel").innerHTML = "";
}
if (this.value) {
$("#orderForm").submit();
}
}
</script>
</head>
<body>
<div>
#using (#Html.BeginForm("GetXML", "Orders", FormMethod.Post, new { id = "orderForm" }))
{
<p>
#Html.DropDownList("productionOrderId",
new SelectList(Model.ProductionOrders, "Id", "OrderNumber"),
"Orders",
new { id = "OrdersSelect", onchange = "DoSubmit();" })
</p>
}
</div>
#if (!Model.PagingInfo.HasAggregations)
{
<div id="noAggDiv">
#Html.Label("No tiene agregaciones", new { #id = "noAggLabel" })
</div>
}
<div id="codesTable">
</div>
</body>
</html>
Why I can't do a submit? I change selected value and nothing happens.
That's because the DoSubmit function isn't called with the element as the context. In the function this will refer to the window object.
You can set the context when you call the function:
onchange="DoSubmit.call(this);"
If you bind the event using jQuery instead of the onchange attribute, the context will be right:
$(function(){
$('#OrdersSelect').change(DoSubmit);
});
Side notes: There is no innerHTML method in jQuery, you would use the text or html method to set the content. You don't have to check if there is any element first, if there is no element, then the jQuery object will be empty, so calling text on it just does nothing.
You should check the content of the value. If you just use it in an if statement it will be converted to a boolean, so an empty string is still evaluated as true.
function DoSubmit() {
$("#noAggLabel").text("");
if (this.value != "") {
$("#orderForm").submit();
}
}
Remove the onchange attribute, and bind through jQuery
<script>
function DoSubmit() {
if ($("#noAggLabel").length) {
$("#noAggLabel").html();
}
if (this.value) {
$("#orderForm").submit();
}
}
$(function(){
$('#OrdersSelect').on('change', DoSubmit);
});
</script>
Also add .length to the $("#noAggLabel") test because it always returns a jQuery object (and it always evaluates to true when used in a boolean test).

HTML Form Questions / Console Log

console.log(value); does not log anything but the number on the left is incrimented everyime i click and it indicates that the console.log() call is made, just not showing what I put into it.
Also, a side question is how could I do this if the javascript is in a different file? Thank you
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Star Delete</title>
<!--<script type="text/javascript" src="StarDelete.js"></script>-->
</head>
<body>OKAY DELETE STAR YES ;D!
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>
</form>
<script type ="text/javascript">
var button = document.getElementById("theButton"),
value = button.form.valueId.value;
//value = document.getElementById("formValueId").value;
button.onclick = function() {
console.log(value);
}
</script>
</body>
</html>
http://jsfiddle.net/3wjRJ/1/
var button = document.getElementById("theButton"),
value = button.form.valueId.value;
Here you go, the issue was that you were declaring the value variable when the javascript was first loaded, therefore it was always blank.

Use javascript to alter submit link

ok so i have a script that when you click a link it dynamicly adds a form field is it possible to make it so when it is submitted it goes to "example.com?7" (7 because of 7 files)
what i mean is if i click it 5 times and there are 5 file fields and i choose 5 files can i make the action link mysite.php?5
here is the script:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="application/javascript">
function add(){
var field = document.createElement('input');
field.setAttribute("type", "file");
field.setAttribute("name", "yo");
document.getElementById('myform').appendChild(field);
}
</script>
</head>
<body>
<form id="myform" name="form1" enctype="multipart/form-data" method="post" action="">
<p>File:
<input type="file" name="hello" id="hello" />
</p>
<p>
<input name="submit" type="submit" value="Submit" />
</p>
</form>
Click Here
</body>
</html>
Thanks a lot!
I suggest giving the new added fields class = "classX" and when you submit the form count the no of elements with the specified class with getElementsByClassName
I find it simpler than incrementing a value each time a field is added
I would keep it simple and keep track of how many file fields you have added. Just update the url every time you add a new file field.
var numFileElements = 1;
function add(){
var field = document.createElement('input');
field.setAttribute("type", "file");
field.setAttribute("name", "yo");
var myForm = document.getElementById('myform');
myForm.appendChild(field);
++numFileElements;
myForm.setAttribute('action', '?'+ numFileElements);
}
Just keep an extra hidden field in the form (call it "count"), and have the script increment its value whenever it adds another file input.
Something like?
function doSubmit() {
var myForm = document.getElementById('myForm'); //Get myForm
var childNodes = myForm.childNodes; //Count child nodes
var fields = 0;
for ( var node in childNodes ) {
if ( childNodes[node].tagName == 'P' ) fields++;
}
myForm.setAttribute('action', 'mysite.php?'+fields);
}
It counts all P elements directly below myForm. Not perfect, but it ought to work! Just add an onsubmit='doSubmit();

jQuery: Count Number of Inputs with a Specific Value

I need to count the number of text inputs with a value of 1.
I have tried the following but with no luck.
$('.class[value="1"]').length
$('.class:contains("1")').length
Using $('.class[value="1"]') technically works, however, if the values in the text input are changed after load, it still counts it as its default load value.
I took a long shot by using the .live click event to get the current value but still no luck.
I had no luck at all using $('.class:contains("1")')
It seems very simple, but has so far eluded me.
This example demonstrates that this works:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#btn").click(function() {
alert($(":input[value='1']").length);
});
});
</script>
</head>
<body>
<input type="text">
<input type="text">
<input type="text">
<input type="button" id="btn" value="How many?">
</body>
</html>
Alternatively you can just loop:
var matches = 0;
$(":input.class").each(function(i, val) {
if ($(this).val() == '1') {
matches++;
}
});
You need to iterate with $.each() if you want current val() values:
k=0;
$('.class').each(function(i, e) {
if ($(e).val() == "1") k++;
});
$(':input.class').filter(function() {
return $(this).val() == '1'
})

Categories

Resources