Javascript 'dynamic' form concatenating string onto form action - javascript

I have the following script constructing a form like so:
var sHTML = "";
sHTML += "<form id='formScore' method='post' action='q_process3.aspx’>";
sHTML += " ";
sHTML += "<input type='hidden' id='Title' name='Title' value= " + title + ">";
sHTML += "<input type='hidden' id='Result' name='Result' value= " + resultstatus + ">";
sHTML += "<input type='hidden' id='ScorePctg' name='ScorePctg' value= " + scorepctg + ">";
sHTML += "<input type='hidden' id='ScorePoints' name='ScorePoints' value= " + scorepoints + ">";
sHTML += "<input type='hidden' id='PassingPctg' name='PassingPctg' value= " + passingpctg + ">";
sHTML += "<input type='hidden' id='PassingPoints' name='PassingPoints' value= " + passingpoints + ">";
sHTML += "<br><input type='submit'><br>";
sHTML += "<form>";
document.getElementById("divEmail").innerHTML = sHTML;
document.getElementById("formScore").submit();
When this submits however, the action/url it points to is:
q_process3.aspx’%3E%20%3Cinput%20type=
So it looks like it is immediately concatenating the 1st input tag onto the the action property of the form element in the string. What am I doing wrong? Or overlooking? I know it's something simple.

In your code typo error
sHTML += "<form id='formScore' method='post' action='q_process3.aspx’>";
^ ^
sHTML += "<form>"; // ought to be </form>
Whether there is reason to submit form immediately?
document.getElementById("formScore").submit();

If I take your code and run it in jsFiddle, I get a long, mangled form action.
If I replace your action's ending smart quote with a plain old tick quote (I'm not sure of the correct namings), the form action is set properly.
Change your form tag string to:
sHTML += "<form id='formScore' method='post' action='q_process3.aspx'>";
That should do it.

Related

How does jQuery().change work with ajax?

I have an input field which I add to html using ajax here:
function WritePrices(categories) {
var strResult = "from: <input class=\"price\" type=\"text\" id=\"minCost\" value=\"" + categories.MinPrice + "\" />";
strResult += "from: <input class=\"price\" type=\"text\" id=\"maxCost\" value=\"" + categories.MaxPrice + "\" />";
$("#price-range").html(strResult);
}
And then I want to catch a moment when this input is changed by the user. That's why in the script I also have change method
jQuery("input#minCost").change(function () {
//...
});
But this method doesn't "hear" any changes to my input field. It hears changes only when my input field is created in html(not during in the script). what should I change to make jQuery seen changes to my input field?
You must assign event just after the creation. Please find working snippet below:
function WritePrices(categories) {
var strResult = "from: <input class=\"price\" type=\"text\" id=\"minCost\" value=\"" + categories.MinPrice + "\" />";
strResult += "from: <input class=\"price\" type=\"text\" id=\"maxCost\" value=\"" + categories.MaxPrice + "\" />";
$("#price-range").html(strResult);
jQuery("input#minCost").change(function () {
alert("working");
});
}
var categories = {};
categories.MinPrice = 0.0;
categories.MaxPrice= 10;
WritePrices(categories);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="price-range"></div>
You need to use document change pattern
$(document).on('change','input#minCost',function(){
...
});

Jquery form inputs not being serialized

So what I'm doing is after an AJAX call, I need to dynamically create a table row containing two hidden inputs, one regular input, and two buttons that have the same functionality as the buttons already on the page when it loads. My problem is that the form I try to serialize is empty, and I'm not sure why.
Here's how I'm generating my html:
function addNewPlayerRow(player, tid) {
var html = "<tr> <form role='form' name='editplayerform'>";
html += "<td>";
html += "<input type='hidden' name='tournamentidform' value='" + tid + "'/>";
html += "<input type='hidden' name='playerid' value='" + player._id + "'>";
html += "<input type='input' class='form-control' name='playername' value='" + player.player_name + "'/>";
html += "</td></form>";
html += "<td>";
html += "<button type='button' class='btn btn-sm btn-success saveplayerbutton' onclick='savePlayerSender(this)'>Save Name</button>";
html += "<button type='button' class='btn btn-sm btn-danger deleteplayerbutton' onclick='deletePlayerSender(this)'>Remove</button>";
html += "</tr>";
$(html).hide().appendTo("#playersbody").fadeIn(300);
}
And here's the onclick function for buttons of the deleteplayerbutton class.
function deletePlayerSender(button) {
var form = $(button).parent().prev().prev();
console.log($(form));
console.log($(form).serialize());
}
When I click the button, the console logs and empty serialization form. Anyone know why?
A simple test like:
console.log($(button).parent().prev().prev().tagName);
should reveal which element you are targeting, which at first look seems to me the <tr> element and not the form. Furthermore, as other suggested you should revisit your html structure. Note that you forgot the closing </td> before the closing </tr>
The button has a reference to the form it belongs to:
<button type="submit" onclick="deletePlayerSender(this)">Remove</button> //add the type submit, which mimics the behaviour of input
var form = $(button).get(0).form; //access the DOM element using get(0)
//alternatively
var $form = $(button).parents('form'); //parents() in plural. Return the form element as jQuery element
console.log(form, $form);
console.log($(form).serialize());
console.log($form.serialize());
check https://jsfiddle.net/dk7qbfpd/. I did some corrections to your code and now is working.
there are some changes in both methods, add and delete
function addNewPlayerRow(player, tid)
{
var html = "<tr><td><form role='form' name='editplayerform" + player._id + "' id='editplayerform" + player._id + "' >";
html += "<input type='hidden' name='tournamentidform' value='" + tid + "'/>";
html += "<input type='hidden' name='playerid' value='" + player._id + "'>";
html += "<input type='input' class='form-control' name='playername' value='" + player.player_name + "'/>";
html += "</form></td>";
html += "<td>";
html += "<button type='button' class='btn btn-sm btn-success saveplayerbutton' onclick='savePlayerSender(" + player._id + ");'>Save Name</button>";
html += "<button type='button' class='btn btn-sm btn-danger deleteplayerbutton' onclick='deletePlayerSender(" + player._id + ");'>Remove</button>";
html += "</td></tr>";
$(html).hide().appendTo("#playersbody").fadeIn(300);
}
function deletePlayerSender(playerId)
{
var form = $("#editplayerform" + playerId);
console.log($(form).serialize());
}
You can't put html where you want,
Form element can't be placed between Table blocks which means it can only
wrap a table, or be placed within td.
Also try replace
.parent().prev().prev()
with
$(button).parent().parent().find('form')
that will support structure changes
Working code below:
function addNewPlayerRow(player, tid) {
var html = "<tr>";
html += "<td><form role='form' name='editplayerform'>";
html += "<input type='hidden' name='tournamentidform' value='" + tid + "'/>";
html += "<input type='hidden' name='playerid' value='" + player._id + "'>";
html += "<input type='input' class='form-control' name='playername' value='" + player.player_name + "'/>";
html += "</form></td>";
html += "<td>";
html += "<button type='button' class='btn btn-sm btn-success saveplayerbutton' onclick='savePlayerSender(this)'>Save Name</button>";
html += "<button type='button' class='btn btn-sm btn-danger deleteplayerbutton' onclick='deletePlayerSender(this)'>Remove</button>";
html += "</tr>";
$(html).hide().appendTo("#playersbody").fadeIn(300);
}
function deletePlayerSender(button) {
var form = $(button).parent().parent().find('form');
console.log($(form));
console.log($(form).serialize());
}
Thanks for all the help, everyone! I managed to fix it by putting the form inside the <td> and then finding the form starting at the button by doing this:
var form = $(button).parent().prev().children("form");

jQuery created element cannot be sent through post

I am dynamically creating input of type text in my form with a value. I can see the new input, but every time I'm sending this through ajax to my php file, it doesn't get the new created input.
The input is put into a table, which is in a form.
I tried with javascript and jQuery, but the two examples do not use the same data, because the javascript way was only for testing purpose
Javascript way
var input = document.createElement("input");
input.setAttribute("type","text");
input.setAttribute("name","moi");
input.setAttribute("disabled","disabled");
input.setAttribute("value","HEY");
$('#actor_form').append(input);
jquery way
var r_name = "<td>" + "<input type='text' name='role[]' disabled value=" +$('#role_name').val()+ " ></td>" ;
var a_name = "<td>" + "<input type='text' name='name[]' disabled value=" +$('#actor_list').val()+ "></td>";
var r_gender = "<td>" + "<input type='text' name='gender[]' disabled value=" +$('#role_gender').val()+"></td>";
var tr = a_name + r_name + r_gender;
$('#actor_table').append("<tr>"+tr +"</tr>");
Sending of data
$.post("assign_roles.php", $("#actor_form").serialize() ,function(data){
alert(data);
});
PHP file
echo $_POST['element'];
The inputs are disabled, so they won't be included in the serialized data.
Ref: http://api.jquery.com/serialize/
"Note: Only "successful controls" are serialized to the string."
Ref: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
"Controls that are disabled cannot be successful."

jQueryUI dialog not displaying

I am trying to generate a jQuery UI dialog using a function. The function is triggered by an onClick event and it is executing, but for some reason the dialog will not display. I'm sure it is something simple.
I would prefer to create the dialog in this way if possible as loading the dialog from a separate html page causes same origin issues on chrome. The code is part of a browser extension that can possibly be used offline so this way allows for that without the same origin restrictions.
I have already created a similar dialog of this nature that worked which had a parameter appended between tags. I have tried that with the current one and it has not worked.
I have the latest jQuery ui and jQuery libs added in the main page.
I'm new to javascript and jQuery but if anyone could provide some help I'd greatly appreciate it.
Thanks,
Joe
function imageSelection() {
var NewDialog = $('<div id="imageSelectionDialog"> ' +
"<ol id= \"selectable\">" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image1.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image2.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image3.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image4.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image5.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image6.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image7.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image8.jpg\"/></li>" +
"</ol>" +
"<form id=\"pieceSelection\">" +
"<div id=\"imageInput\">" +
"<input type=\"text\" id=\"image\" value=\"images/stock/walkin.jpg\"" +
"title=\"Select an image above or Paste a URL e.g http://server.com/path/to/image.jpg\"/>" +
"</div>" +
"<div id=\"radio\">" +
"<input type=\"radio\" id=\"radio1\" name=\"radio\" checked/>" +
"<label for=\"radio2\">x3</label>" +
"<input type=\"radio\" id=\"radio2\" name=\"radio\"/>" +
"<label for=\"radio3\">x4</label>" +
"<input type=\"radio\" id=\"radio3\" name=\"radio\"/>" +
"<label for=\"radio4\">x5</label>" +
"<input type=\"radio\" id=\"radio4\" name=\"radio\"/>" +
"<label for=\"radio5\">x6</label>" + 7
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
"<label for=\"radio6\">x7</label>" +
"<input type=\"radio\" id=\"radio6\" name=\"radio\"/>" +
"<label for=\"radio7\">x8</label>" +
"<input type=\"radio\" id=\"radio7\" name=\"radio\"/>" +
"<label for=\"radio8\">x9</label>" +
"</div>" +
"</form>" +
'</div> ');
NewDialog.dialog({
autoOpen: false,
modal: true,
height: 500,
width: 500,
title: 'Choose an image',
buttons: {
"Ok": function() {
$(this).dialog("close");
}
}
});
return false;
}​
You seem to have an unexpected 7 within your string which makes this concatenation invalid, causing a Uncaught SyntaxError: Unexpected string.
Change this:
"<label for=\"radio5\">x6</label>" + 7
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
to either this:
"<label for=\"radio5\">x6</label>" +
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
or this:
"<label for=\"radio5\">x6</label>" + 7 +
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
In addition you need to set autoOpen to true if you want the dialog to be visible immediately.
DEMO - Removing the 7 and set autoOpen to true
You do not seem to be appending the HTML to the DOM to make it work..''
Append it to the body before you assign it to a Do=ialog and it should work..
var html = '<div id="imageSelectionDialog"> ' +
//other html ;
$('body').append(html);
var NewDialog = $("#imageSelectionDialog");
// Code to Initialize the dialog

Javascript passing parameters from form to function --> update DB

can anyone help please. I have a form generated dynamically, when it is submitted it should send values to a function and add them back to a database. I'm having real problems getting this to work, it seems simple: 1. Form --> 2. submit received --> 3. update function. The code is below:
Dynamically generated form:
function renderResults(tx, rs) {
e = $('#status');
e.html("");
for(var i=0; i < rs.rows.length; i++) {
r = rs.rows.item(i);
var f = $("<form>" +
"<input type=\"hidden\" name=\"rowId\" value=\"" + r.id + "\" />" +
"<input value=\"" + r.name + "\" name=\"name\" />" +
"<input value=\"" + r.amount + "\" name=\"amount\" />" +
"<input type=\"submit\" />" +
"</form>");
e.append("id: " + r.id, f);
f.submit(function(e)
{
updateRecord(this.rowId.value, this.name.value, this.amount.value);
});
}
}
Handles the form submit and passes to function:
$('#theform').submit(function() {
updateRecord($('#thename').val(), $('#theamount').val());
});
Function to set values:
function updateRecord(id, name, amount) {
db.transaction(function(tx) {
tx.executeSql('UPDATE groupOne SET (name, amount) VALUES (?, ?) WHERE id=?', [name, amount, id], renderRecords);
});
}
The DB update code has the id set to 4 as a test just to see if anything happens to row 4, i've been fiddling with this line for ages to get it to work. If i set it to:
tx.executeSql('UPDATE groupOne SET name = 4, amount = 5 WHERE id=?', [id], renderRecords);
it will work with set values, but can someone help me get the form values into it please.
You are missing the row id in your jQuery selector. You are passing:
$('#thename').val();
But your field has an id of "thename" + r["id"]:
'<input type="text" ... id="thename' + r['id'] + '" ...>'
You need to get your value by passing the full input id.
$("#thename" + rowId).val();
Edit: Looking more closely at your code, I notice you are creating multiple forms with the same id, which is invalid html. I see now that you've got one form per record. Good, just lose the id from the form and its inputs. Instead, use names for the inputs.
var f = $("<form>" +
"<input type=\"hidden\" name=\"rowId\" value=\"" + r.id + "\" />" +
"<input name=\"name\" />" +
"<input name=\"amount\" />" +
"<input type=\"submit\" />" +
"</form>");
e.append("id: " + r.id, f);
f.submit(function(e)
{
updateRecord(this.rowId.value, this.name.value, this.amount.value);
});

Categories

Resources