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");
Related
This is app running in electron framework. The html is inserted as iFrame into main html.I have button with id. I want to enable and disable this button based onkeypressed event. I will paste the code what I tried.
File.js
function buttonEnable(){
document.getElementById("Btn").disabled = false;//trying to enabl or disable
button with the help of Id
}
function setData(){
document.getElementById("proxyBtn").disabled = true;
let FileData= "<form>";
FileData+= '<td class="hostid-td-padding">';
FileData+= "<input id=\"user\" type=\"text\" value=\""+user+"\"
onkeypress=\"buttonEnable()\"></input>";
xmlFileData+= "</td>\n";
FileData+= '<td>';
FileData+= "<input id=\"Btn\" type=\"submit\" value=\"Save\"
onclick='update()'></input>\n";
FileData+= "</td>";
FileData+= "</tr>\n";
FileData+= "</form>";
}
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(){
...
});
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.
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
I have a button that when clicked inserts a form input field and a button (to delete) into the form using JQuery .after(). This works fine.
The button that is inserted has a function .click that should run when it is clicked - it is not working.
<script type="text/javascript">
$("#addAQuestion").click(function(){
var begin = "<tr>";
var question = "<td><input type='text' name='question'/>";
var deleteButton = "<input type='button' class='deleteQuestion' name='delete' value='Del' /></td>";
var end = "</tr>";
$("#questions").after(begin + question + deleteButton + end);
});
$(".deleteQuestion").click(function(){
alert('test');
//$(this).parent().empty();
});
</script>
How come the alert is not being triggered when a user clicks on the .deleteQuestion button?
Thanks!
Order of execution. The code that adds the nodes to the DOM is asynchronous - it happens on click. So, essentially, you're attaching click events to .deleteQuestion nodes before those elements are in the DOM.
There are two ways to fix this.
1) Fix the order of execution so that the click events will be properly attached
<script type="text/javascript">
$("#addAQuestion").click(function(){
var begin = "<tr>";
var question = "<td><input type='text' name='question'/>";
var deleteButton = "<input type='button' class='deleteQuestion' name='delete' value='Del' /></td>";
var end = "</tr>";
$("#questions").after(begin + question + deleteButton + end);
// Has to be here, right after they're added to the DOM
$(".deleteQuestion").click(function(){
alert('test');
//$(this).parent().empty();
});
});
</script>
2) Or, you can use jQuery's live() function to handle this for you via event delegation
<script type="text/javascript">
$("#addAQuestion").click(function(){
var begin = "<tr>";
var question = "<td><input type='text' name='question'/>";
var deleteButton = "<input type='button' class='deleteQuestion' name='delete' value='Del' /></td>";
var end = "</tr>";
$("#questions").after(begin + question + deleteButton + end);
});
$(".deleteQuestion").live( 'click', function(){
alert('test');
//$(this).parent().empty();
});
</script>
Because the delete button doesn't exist when you do your event wireup.
Consider looking into the .live() api of jquery to solve this problem, or else put the wiring to the delete button click inside the other click handler (so it wires up after the button is added)
Also, you should really consider looking into dom manipulation apis instead of string concatenation.
You aren't assigning the event to the dom object when you are adding it, change the code as follows:
<script type="text/javascript">
$("#addAQuestion").click(function(){
var begin = "<tr>";
var question = "<td><input type='text' name='question'/>";
var deleteButton = "<input type='button' class='deleteQuestion' name='delete' value='Del' /></td>";
var end = "</tr>";
$("#questions").after(begin + question + deleteButton + end);
$(".deleteQuestion").click(function(){
alert('test');
//$(this).parent().empty();
});
});
</script>
This should work:
<script type="text/javascript">
$("#addAQuestion").click(function(){
var begin = "<tr>";
var question = "<td><input type='text' name='question'/>";
var deleteButton = "<input type='button' class='deleteQuestion' name='delete' value='Del' /></td>";
var end = "</tr>";
$("#questions").after(begin + question + deleteButton + end);
$(".deleteQuestion").click(function(){
alert('test');
//$(this).parent().empty();
});
});
</script>