Can't find form after injecting it with jQuery(I think) - javascript

Im adding the form, in an on-click event, to a row in a table using (Sorry about the really long row):
$('#row'+rowvalues[0]).html('
<form id="updform'+rowvalues[0]+'">
<td>'+rowvalues[0]+'</td>
<td>
<input type="text" name="namn'+rowvalues[0]+'" value="'+rowvalues[1]+'">
</td>
<td>
<input type="text" name="ingred'+rowvalues[0]+'" value="'+rowvalues[2]+'">
</td>
<td>
<input type="number" name="pris'+rowvalues[0]+'" value="'+rowvalues[3]+'">
</td>
<td>
<input type="number" name="fampris'+rowvalues[0]+'" value="'+rowvalues[4]+'">
</td>
<td>
<Button class="upddatasave" id="sub'+rowvalues[0]+'">Submit</button>
</form>
</td>
');
intialiseUpdatebutton();
then I initialize the button using the fuction called intialiseUpdatebutton();
that function looks like:
function intialiseUpdatebutton() {
$(".upddatasave").on("click", function() {
var butid = $(this).attr('id');
var dataid = parseInt(butid.slice(3));
console.log(dataid);
console.log($('#namn'+dataid).val());
var formvalues = $('#updform'+dataid).serializeArray();
console.log(formvalues);
});
}
It finds the button and it works, but I can't find the form. My guess was that it cant find the injected form, but if that's the case how do I fix it? like I do with the initialise function for the button.
What Im trying to do: Im displaying data from an SQL table in a table in html - It has 2 buttons 1 update and 1 delete. Im trying to fix the update button so that when I press it the cells with the values change into a form with textfields and the values in there and then you can just change the values and press submit to save the changes.
Edit: jsfiddle.net/rh8deo79/2 <- jsfiddle

By editing your formmatting job to break up the massive one-liner, I found that you end your <form> before your <td>, which is invalid html and probably your source of error.

You need to reorganize your tags. You can't have <tr><form><td>, as described here.
You might try creating a new table inside each form.

Related

Change div color on checking all check boxes in hidden form

Have several problems and can't find solution. My code https://jsfiddle.net/46qybyrh/2/
Upper table HTML
<div class="block">
<table>
<tr>
<th>Nr.</th>
<th style="width: 200px">Task</th>
<th>Progresas</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td>Air port scedules</td>
<td>0/3</td>
<td>
<button onclick="showDiv()">Expand</button>
</td>
</tr>
</table>
Hidden div
<div id="popup" class="popupbox">
<table class="block">
<tbody>
<tr>
<td></td>
<form>
<td>XML</td>
<td>
<span>Comment</span><br>
<textarea></textarea>
</td>
<td>
<span>Deadline</span>
<input type="date" value="2017-08-24">
</td>
<td>Done:<input type="checkbox"></td>
<td><input type="submit" value="Apply"></td>
</form>
</tr>
<tr>
<td></td>
<form>
<td>Scedules</td>
<td>
<span>Comment</span><br>
<textarea></textarea>
</td>
<td><span>Deadline</span>
<input type="date" value="2017-08-10">
</td>
<td>Done:<input type="checkbox"></td>
<td><input type="submit" value="Apply"></td>
</form>
</tr>
<tr>
<td></td>
<form>
<td>Infobox</td>
<td>
<span>Comment</span><br>
<textarea></textarea>
</td>
<td><span>Deadline</span>
<input type="date" value="2017-08-14">
</td>
<td>Done:<input type="checkbox"></td>
<td><input type="submit" value="Apply"></td>
</form>
</tr>
</tbody>
</table>
<button onclick="hideDiv()">close</button></div>
Main aims of this code should be:
When press apply on each row, hidden div should not hide. Only information like comment, date, check box should change.
When all 3 check boxes are selected, upper tables first row (1 Air port scedules 0/3) should change its background color.
If deadline is close (let say 5 days till deadline) entire row should change background color.
If deadline is passed entire row should change its background color.
I know its a lot to ask but maybe someone of you will guide me on each of this steps.
I took your fiddle and put it into a codepen and messed around with it for a while. I was able to do what you wanted with a lot of jQuery. To learn jQuery, try www.w3schools.com/jQuery.
Here is the codepen:
https://codepen.io/pen/Ojxzje
In a few short steps:
I removed all the <form> tags, <input type='submit'>, and <tbody> to make the code cleaner (the submit button was causing problems with hiding the div as mentioned by #AngeLOL.
I reformatted the lower table a bit just to make it cleaner for my jQuery to work nicely. (I added a header row and removed the text from the blocks)
I included the jQuery library
I renamed your jQuery functions and created one more (open(), close(), and apply(). They are called by the buttons respectively.
Inside the open() function, I showed the rows in the second table with the class if items-[ID OF LIST WE ARE IN]. This way there could be a clean list of all of the tasks instead of having a new table for every new list.
The open() function also changes the button from expand to hide which calls the close function.
The close() function just hides the second table and changes the name of the button back to expand.
The apply() function is run whenever you press the Apply button. It performs two checks:
Checks all of the checkboxes in the table rows labeled .details-[ID WE ARE WORKING WITH] and if they are all checked, selects the list's row in the upper table. It adds a green color to the background.
It then finds all the dates and compares them with today's date (thanks again #angeLOL. If the date is within 5 days, it selects the row the date was on and changes the color. If the date has passed or is today, it colors the row red.
It's a lot of code and a bunch of reorganization, so let me know if you are having trouble understanding it and I can help walk through my steps.
use <button type="button">Apply</button> instead <input
type="submit" value="Apply">
Give to those elements you want to change its color an "id" attribute, so change its color by using style propierty of element
document.getElementById("elementID").style.backgroundColor = "#colorcode"
Here is an example of how to compare dates.
Hidden div is initially hidden. When you submit the form, you reload the page, so it is hidden again. You may want to handle click on button or form submit, prevent default behavior, submit data via AJAX request and then update your UI without page reload.
<form onsubmit="return handleSubmit(this);">
...
<input type="checkbox" onchange="updateCheckboxesState();">
</form>
<script>
function handleSubmit(form) {
// send AJAX request here...
// manipulate DOM if needed in AJAX callback
return false; // prevent submit
}
function updateCheckboxesState() {
var checkboxes = document.querySelectorAll("form input[type=checkbox]");
for (var i = 0; i < checkboxes.length; i++) {
if (!checkboxes.item(i).checked) return; // break on first unchecked
}
// highlight the row here...
}
</script>
Similar flow can be applied to date inputs. The main idea is to update UI when value has been changed.
Background change can be achieved via changing element's inline style or changing it's class
var el = document.querySelector("div.block > table > tr");
el.style.backgroundColor = "#FF0000"; // inline
el.className = "highlighted"; // element class
Hope, this helps...

How can I add "tags" to a search field using Jquery

I have some tags (tagbutton) in a table, each tag has its own id, what I want to achieve is when the user clicks on the tag, a hidden input is created in the form with the value of the div (or tag) that has been clicked on. I also want the clicked div to be copied in the tagselected div.
I have no idea how to do that on jquery. Thank you very much in advance for your help.
<table> <tr>
<td> <div class="tagbutton" id="jazz"> Jazz </div> </td>
<td> <div class="tagbutton" id="classical"> Classical </div> </td>
<td> <div class="tagbutton" id="R&B"> R&B </div> </td>
</tr> </table>
<div id="tagselected"> </div>
<form> <input type="text"> <button ="submit"> Submit </button> </form>
Here is the javascript function that I have to copy the div, however when I clicked on it the entire table is copied
$('#jazz').click(function () {
$('.tagbutton').clone().insertAfter("#tagselected");
});
This code is wrong:
$('#jazz').click(function () {
$('.tagbutton').clone().insertAfter("#tagselected");
});
The problem with this code is that you are retrieving all the items with class tagbutton on the whole page. If your click function is on the item you want then you should be able to just use this to access the clicked item.
so something like :
$(this).clone().insertAfter("#tagselected");
This code is not tested and is just the simple change of the initial jQuery selector.
I assume the problem you have with the hidden fields is the same - that you were selcting all tags instead of just the one you clicked so hopefully this will solve that problem too.

JS verify form data inside ajax-returned html

Ajax-returned HTML includes a table and a submit button (type=button)
The table includes jQuery routine to clone table row (each row allows choosing/uploading one file, and has two values: <input type="text"> for doc title, and <input type="file">.
<table id="MyTable">
<tr name="tr3" id="tr3">
<td>
<input type="text" name="dt[]" id="dt1">
</td>
<td>
<input type="file" name="fff[]" id="ff1">
</td>
</tr>
</table>
<input type="button" name="sub1" id="sub1" value="Submit" onclick="checkform();">
Upon form submit, I must check that each doc title has been filled-in, so the submit button calls a javascript routine:
function checkform()
{
if(document.updateprojectdocs.dt[0].value=='')
{
alert("Fields marked with an asterisk are required.");
document.updateprojectdocs.dt[0].focus();
return;
}
document.getElementById("TheForm").submit();
}
Of course, this does not work (script dies before form submit -- but submits if I remove the preceeding if structure). Can anyone tell me why and how to fix?
Also, there will be an indeterminate number of dt[] fields to check. How could I structure a loop to do this? I suspect jQuery's .find().each() could be used, but not sure what that would look like?
UPDATES:
Thanks to DaHaKa's response below, I am closer to a solution. I mod'd DaHaKa's suggested code into jQuery.
I was having trouble communicating with DaHaKa - for some reason his responses were not appearing until long, long, long after he posted them (the problem was probably on my end). While I was waiting (hours), I posted part of the problem in another question and ended up resolving it there. That other question grew into the FULL CORRECT ANSWER, and I direct future viewers there. Note that user thecodeparadox created a working JSFiddle of the full solution.
I have awarded this question to DaHaKa as he was more than willing and able to assist, but comm problems intervened. Thanks again, D.
In this case jQuery each function isn't neccessary, you can do it simple like this =>
try
<table id="MyTable">
<tr name="tr3" id="tr3">
<td>
<input type="text" name="dt" id="dt1">
</td>
<td>
<input type="file" name="fff" id="ff1">
</td>
</tr>
</table>
<input type="button" name="sub1" id="sub1" value="Submit">
JavaScript
document.getElementById("sub1").onclick = function(){
if (document.getElementById("dt1").value!=""){
document.getElementById("TheForm").submit();
} else {
alert("Empty Field(s) !");
}
};
you should use ids in JavaScript from html tags , NOT NAME tags
And whats about you file input , you could understand it from your server side scripting language like php , with super global variables $_FILES['file']['error'] types

Change script to enter text in a div, not textarea

I'm working on a job with a developer who is taking care of coding that's beyond my ability; mostly PHP and more complex Javascript (I'm only okay at jQuery).
Part of the work the developer has been doing involves checking a database and dynamically entering results into the page. The problem is that currently these results are entered into a <textarea>, which is not ideal as it means that if it's readonly, the results cannot be deleted if the user changes their mind. If it's not readonly, the user can enter any text they like into the textarea, rendering the page unusable. In addition, I'm unable to apply any CSS to the results within the textarea.
Also, the developer is using tables, one of my pet hates.
I would like the <textarea> to be instead a <div> containing a <div> for each database result found.
The developer is currently away for a few weeks and I would prefer to get this done sooner rather than later. I've tried changing "td" simply to "div" but obviously that didn't work.
I'd really appreciate some help. I've included the code below. Unfortunately, I'm unable to give access to the live/testing site (beyond my control) and apologise for that.
if(answer)
{
var newRow = document.getElementById("target_table");
var Row = newRow.rows.length;
var row1 = newRow.insertRow(Row);
var index=row1.rowIndex;
var td1= document.createElement("TD")
var td2= document.createElement("TD")
td2.innerHTML = "
<INPUT TYPE='hidden' NAME='course"+Row+"' id='course"+Row+"' value='"+answer+"'>
<INPUT TYPE='hidden' NAME='ary"+Row+"' id='ary"+Row+"'>
<INPUT TYPE='hidden' NAME='Dary"+Row+"' id='Dary"+Row+"'>
<p class='courseName'>"+answer+"</p>
<div id='boxRw"+Row+"' class='boxyHolder'>
<TABLE border=1 cellspacing=2>
<TR>
<TD>
<INPUT TYPE='button' name='Add a favourite to this course' value='Add a favourite to this course' onclick='javascript: window.open(\"<?=$path?>add-my-favourites/"+Row+"\",\"mywindow\",\"left=550,top=200,width=400,height=350,toolbar=1,resizable=0\");'>
</TD>
</TR>
<tr>
<td colspan=2>
<TABLE border=1>
<TR>
<TD valign=top>Favourites:</TD>
<TD>
<TEXTAREA class='fav-box' NAME='reps"+Row+"' id='reps"+Row+"' ROWS=4 COLS=45></TEXTAREA>
<input class='fav-box' TYPE='hidden' NAME='repsId"+Row+"' id='repsId"+Row+"' value=''>
</TD>
</TR>
</TABLE>
</td>
</tr>
</TABLE>
</div>";
row1.appendChild(td1);
row1.appendChild(td2);
document.getElementById("h").value=Row;
}
function setVal(){
var r = "<?=$_GET['hVal']?>";
var y = "reps"+r;
var y1 = "repsId"+r;
window.opener.document.getElementById(y).value+=document.frm.favourites.value+',';
window.opener.document.getElementById(y1).value+=document.frm.recp_listId.value+',';
window.close();
}
Edit: I believe these are the lines I need to change:
window.opener.document.getElementById(y).value+=document.frm.recipes.value+',';
window.opener.document.getElementById(y1).value+=document.frm.recp_listId.value+',';
I think the problem is that these lines are adding the value to what is currently a <textarea>. When I change the textareas to divs, the values are not applied to the divs. So I need to change the code so that it enters the results as text in the divs - not values.
If you use a div, use its textContent property, not value like you'd use for form controls such as textarea and input. You are getting no error because you're ending up creating a value property on the div.
Code snippet #1
var div = document.createElement('div');
div.textContent = document.frm.recipes.valu‌​e;
window.opener.document.getElementById(y).appendChild(div);

How to delete a particular row in a dynamically created html rows using Javascript DOM?

Here am trying to add a html rows by clicking on the add button and delete the added rows on clicking on the delete button.
Its working fine with adding rows as expected. But the problem is the delete function deletes the last row of the table instead of deleting that corresponding row.
As there is delete button in every row, only that corresponding row should be deleted when the delete button is clicked.
Here is the jsfiddle which demonstrates the situation better.
if the fiddle above failed to load as it does, Please refer the code below.
Thanks in advance
JAVSCRIPT
//function to add a row
function insSpec()
{
rl=document.getElementById("insSpecc").rows.length;
var a=document.getElementById("insSpecc").insertRow(rl);
var h=a.insertCell(0);
var f=a.insertCell(1);
var m=a.insertCell(2);
var n=a.insertCell(3);
h.innerHTML='<div class="separator"><input type="text" name="client_prod[]" class="separator" id="competitor_prod'+rl+'" style="width:150px" >';
f.innerHTML='<input type="text" name="client_nrx[]" id="client_nrx'+rl+'" size="5" />';
m.innerHTML='<input type="text" name="client_rrx[]" id="client_rrx'+rl+'" size="5" />';
n.innerHTML='<button class="del_img" onClick="delSpec('+rl+')">Delete</button></div>';
}
//function to delete a row
function delSpec(rl)
{
r=document.getElementById("insSpecc").rows.length;
if(r!=2)
{
document.getElementById("insSpecc").deleteRow(r-1)
}
}
HTML
<table id="insSpecc" width="100%;">
<div class="separator">
<tr>
<td><span>Product</span></td>
<td><span>NRX(Qty)</span></td>
<td><span>RRX(Qty)</span></td></tr></div>
<tr>
<td><input type="text" id="client_prod" name="client_prod[]" style="width:150px;" class="validate[required] text-input"></td>
<td>
<input type="text" id="client_nrx" name="client_nrx[]" size="5" class="validate[required] text-input">
</td>
<td>
<input type="text" id="client_rrx" name="client_rrx[]" size="5">
</td>
<td>
<button id="add_img" id='insSpecimg' style='display:block;' onClick="insSpec()" align="center">Add</button>
</td>
</tr>
</table>
Try to use
n.innerHTML='<button class="del_img" onClick="delSpec(this)">Delete</button></div>';
and later
function delSpec(node)
{
r=node.parentNode.parentNode;
r.parentNode.removeChild(r);
}
in such case delSpec will receive pointer to the button, and will be able to delete the necessary row.
document.getElementById("insSpecc").deleteRow(r-1)
which should be
document.getElementById("insSpecc").deleteRow(rl);
You should use id for each row, and u can delete that row with the ID... There are several ways to get a DOM element object in jQuery and other libraries.
All you need to do is, use getElementById("the id of the row") and store that element in a variable, or make it's innerHTML=""; or delete it like xdazz suggested.
You can also get elements with class names... so, if your row is using any css class, you can get that row like you did with the ID.
Aquatic is also right: you either need to access all the DOM, traverse it, and reach ur desired element and do whatever with it, or access it with element's id or class name.
You can also change ur html markup for each row to have a check box which tells which rows to delete... and for each row if a checkbox is selected, delete the row.
Vote up if you got the point.

Categories

Resources