How to remove displayed value from td and replace with input field? - javascript

I have dynamic table that display names and input fields. If name is displayed in table row user have option to delete that name. I know how to remove value from specific table row but I have problem replacing that same spot with input field that should be the same as other available fields. Here is my code that I have so far:
<cfoutput>
<tr>
<td>#TimeFormat(CurrentTime,'hh:mm tt')#</td>
<td onClick="deleteSlot('#TimeSlotID#')">
<cfif UserID GT 0>
<label>
<div id="#TimeSlotID#">
(<b>#First# #Last#</b>)
<img src="images/delete.png"/>
</div>
</label>
<cfelseif UserID EQ -1>
<label>
<input type="text" name="email" id="email#currentRow#" class="email">
<input type="button" name="slot" id="slot#currentRow#" class="slot" value="Save" onClick="saveTime(this,'#TimeSlotID#')" style="display: none">
</label>
</cfif>
</td>
</tr>
</cfoutput>
JavaScript:
//This code display save button if user start typing in available field.
$(document).ready(function() {
$(".email").keyup(function(e) {
if($(this).val() != '') {
$(".email").not(this).attr('disabled','disabled');
$(this).next(".slot").show();
} else {
$(".email").removeAttr('disabled');
$(this).next(".slot").hide();
}
});
});
//This is the code where I'm trying to remove name from the cell and replace with input field
function deleteSlot(TimeSlotID){
$('#' + TimeSlotID).replaceWith('<label><input type="text" name="email" id="email#currentRow#" class="email"><input type="button" name="slot" id="slot#currentRow#" class="slot" value="Save" onClick="saveTime(this,'#TimeSlotID#')" style="display: none"></label>');
}
This code that I currently use in deleteSlot function does replace name with input field but if I start typing in that field I do not have Save button showed up like in the others. I'm not 100% sure if this can be done the way I started or I should use something else. I tried append but that did not work, gave me extra input fields every time I clicked. If anyone knows better way to fix this please let me know.

I believe the event keyup needs to be re-applied:
$(document).ready(function() {
applyKeyUp();
});
function applyKeyUp() {
$(".email").keyup(function(e) {
if($(this).val() != '') {
$(".email").not(this).attr('disabled','disabled');
$(this).next(".slot").show();
} else {
$(".email").removeAttr('disabled');
$(this).next(".slot").hide();
}
});
}
function deleteSlot(TimeSlotID){
$('#' + TimeSlotID).replaceWith('<label><input type="text" name="email" id="email#currentRow#" class="email"><input type="button" name="slot" id="slot#currentRow#" class="slot" value="Save" onClick="saveTime(this,'#TimeSlotID#')" style="display: none"></label>');
applyKeyUp();
}

The issue is with weirdness of the id you are passing.Since the id is already having '#' in front of it, the jquery selector would not be able to apply the target by id. If you really need '#' in front of the id, then you need to apply id equal to selector.
$('#' + TimeSlotID)
should be
$("[id = '" + TimeSlotID + "']")
Example : https://jsfiddle.net/DinoMyte/6d5ry9br/5/

Related

JavaScript only changes text of first iteration with thymeleaf

I hope you are all well.
I have a school assignment, and I want to dynamically be able to change the name of a 'project'. This assignment is about projects. The way I've done it right now works with the first 'project' from a list of 'projects' iterated through with thymeleaf. I'm aware that what I've done right now is absolutely bad code behavior, but we have had no teaching in JS yet. But I really wanted this feature.
I don't know how to make this work for each project preview, right now it works for the first preview, but for the rest it just erases the project name from database. (see picture)
<div class="projects" th:each="projectNames : ${listOfProjects}">
<form action="deleteProjectPost" method="post">
<input type="hidden" th:value="${projectNames.projectID}" name="deleteID">
<input type="image" src="delete.png" alt="Submit" align="right" class="deleteProject" onclick="return confirm('Are you sure that you want to delete this project?')">
</form>
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text()" align="right" class="editProject">
</form>
<form action="/projectPost" method="post">
<input class="projectInfo" name="projectID" type="text" th:value="'Project No.: ' + ${projectNames.projectID}" readonly="readonly">
<input class="projectInfo" type="text" th:value="'Project name: ' + ${projectNames.projectName}" readonly="readonly">
<input class="projectInfo" type="text" th:value="${projectNames.projectStartDate} + ' - ' + ${projectNames.projectEndDate}" readonly="readonly">
<input type="submit" value="OPEN" class="openProject">
</form>
</div>
<script>
function change_text() {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = document.getElementById("oldName").value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
document.getElementById("newName").value = changedText;
}
</script>
First form in HTML is the red cross to delete an entire 'project'. Second form is what is intended to change the name displayed on the 'project preview', but only works on first preview and deletes project name from the rest. Last form is the actual preview. I couldn't find another way to have multiple forms and do different POSTS while working with Java Spring and Thymeleaf.
My wish is to make the change_text() function work for each 'project preview'
Best regards!
function change_text(imageInput) {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = imageInput.parentNode.querySelector('.old-name').value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
imageInput.parentNode.querySelector('.new-name').value = changedText;
}
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" class="old-name" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" class="new-name" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text(this)" align="right" class="editProject">
</form>
Ok so I made a few changes. First, notice the inputs with oldName and newName now have classes on them. These can be repeated. If you are not using the ids for anything other than the script, you should remove them. Otherwise if you have styling rules for them you should consider changing those CSS rules to use the class instead so you can remove the invalid repeating ids.
Secondly, the onlick of the image now passes in this. What that does is it passes in the actual input that the user clicked, so you have some context into which form element the user is interacting with.
Then looking at the logic, the method now accepts in imageInput which is the this from the onclick.
Using imageInput.parentNode we go up the DOM Tree to the parent element of the input, which is the form in this case. We can then turn around and use querySelector to find the other element in the form we want to manipulate. And it will only find the element in our particular form because that is what we are selecting off of.

getting input value after it has been formatted to currency with jquery

I have a form. On this form I when I add line items I save the input value then prepend it to the form. This part works. Keep in mind the form is not being submitted I am just adding to the dom dynamically
In the part of the form I save there is a price input. I am using jquerypriceformat plugin to format the price into price format. For example 111 becomes $1.11. If I do not use the plugin it works. The plugin does work as intended. I think my problem is that after I type the value is being changed and I need to retain that value somehow.
Here is a fiddle
https://jsfiddle.net/ks2z5mdo/7/
I think the fiddle will better show what the problem is. Basically when you type a description type a quantity and price, the price gets formatted then hit the add button all the data is saved except the price.
How can I solve this?
So first is the form
<div class="form-row">
<strong>Line Items:</strong>
<br>
<div class="line-items">
<div class="line-item">
<div class="line-item-box description">
<label>Description:</label>
<textarea name="description" id="description"></textarea>
</div><!--
--><div class="line-item-box quantity">
<label>Quantity:</label>
<input type="text" name="quantity" id="quantity">
</div><!--
--><div class="line-item-box price">
<label>Price:</label>
<input type="text" name="price" id="price">
</div>
<button class="btn add-item">Add Item</button>
</div>
</div>
</div>
Then is the jquery
$(document).ready(function() {
$('#price').priceFormat();
$('.add-item').click(function() {
if ($('description, #quantity, #price').filter(function() { return $(this).val(); }).length > 0) {
var description = $('#description').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
$('.line-items').prepend('<div class="line-item"><div class="line-item-box description">' + description + '</div><div class="line-item-box quantity">' + quantity + '</div><div class="line-item-box price">' + price*quantity + '</div><button class="btn remove-btn">Remove</button></div>');
return false;
} else {
alert('Line item empty');
}
});
$(document).on('click', '.remove-btn', function() {
$('.line-item').remove();
});
});
Your var price = $('#price').val(); adds a $ and a space in front of the actual value that you are trying to get. Therefore, one solution is to get the substring of this value to remove the $:
var price = $('#price').val().substring(2);
This will leave the value as a number rather than the string it was originally made to be. Here is a fiddle that works.

How to only show a div if a certain entry field is filled in (but not submitted)?

Relatively new to html coding, and very new with javascript. On this page, I don't want the option to email an editor to become visible until a tripID is filled in (but form not submitted yet). Here is the form so far without that option added yet:
TripID:
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' /><br><br>
Port:
<input type='text' id='aport' name='aport' size='6' maxlength='6' /><br><br>
<div id=acheckbox><br> E-mail editor? </b>
<input type='checkbox' name='acheck' onchange='copyTextValue(this);'/><br>
<div id='div' style='display:none'>
<br> <b>Subject:</b> <input type='text' id='asubject' name='asubject' size='70' maxlength='75'/><br><br>
<textarea name='aemailbody' cols='85' rows = '10'>Explain any packaging or labeling mistakes here...</textarea>
</div>
</div>
<script>
function copyTextValue(bf) {
if(bf.checked){
document.getElementById('div').style.display = 'block';
var atext = 'Frozen Sample Error Notice: '+ document.getElementById('atripid').value;
}else{
document.getElementById('div').style.display = 'none';
var atext = '';
}
document.getElementById('asubject').value = atext
}
</script>
</div>
Now to hide the email editor option until tripid is filled in, I got something like this to work on jfiddle:
<form action="">
tripid:<input type="atripid" id="atripid" value="">
port:<input type="aport" id="aport" value="">
</form>
<div id="acheckbox" style="display:none">
<br><br><br>
This is where the email options (subject and textbox) would appear.
</div>
<script>
$("#atripid").keyup(function(){
if($(this).val()) {
$("#acheckbox").show();
} else {
$("#acheckbox").hide();
}
});
</script>
But for some weird reason, it won't work anywhere else, so I can't figure out how to incorporate it into what I already have. Does anyone have any ideas that could help me? Thanks!
You can do something like this with pure javascript:
<input type="atripid" id="atripid" value="" onkeyup="keyupFunction()">
And define your keyupFunction().
See jsfiddle
The code you attempted on jsfiddle requires that you import jquery.js files. An alternate way of doung what you intend to do is
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' onkeyup="toggleCheckBox(this)" />
<input type='checkbox' name='acheck' id="acheckbox" style="display:none;" onchange='copyTextValue(this);'/>
with js
function toggleCheckBox(element) {
if(element.value=='') {
document.getElementById('acheckbox').style.display = 'none';
}
else {
document.getElementById('acheckbox').style.display = 'block';
}
}
The issue is the .keyup() method, which is not consistent across browsers and does not account for other means of user input. You would rather, use an Immediately Invoked Function Expression (IIFE) that will detect the propertychange of the input field in question and then to fire the desired event if the condition is met. But for the purposes of simplicity, and the fact that I'm not as well versed enough in IIFE syntax, simply bind some events to the input field, like so:
$("#atripid").on("keyup change propertychange input paste", (function(e) {
if ($(this).val() === "") {
$("#acheckbox").hide();
} else {
$("#acheckbox").show();
}
}));
#acheckbox {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="">
tripid:
<input type="atripid" id="atripid" value="">port:
<input type="aport" id="aport" value="">
</form>
<div id="acheckbox">
<br>
<br>
<br>This is where the email options (subject and textbox) would appear.
</div>

How to extract form element values in a loop?

I have a list of form elements that I want to loop over to get the values of, so if someone typed their name in the input i want their name, if they selected an option from a select box I want the not the numerical value but the string. All these values needs to be outputted as one string.
This is the loop i've created, I however have no idea how to go about this problem..
every form element has a name starting with credit_
if someone could point me in the right direction it would be much appreciated..
$(this).parent().parent().find('[name*=credit_]').each(function( index ){
});
my html is quite simple.
<div class="comp-row">
<!-- a select -->
<!-- an input -->
</div>
This is part of the form, there are many other form fields but im only concerned with the ones within "comp-row" which Im manipulating a lot.
I ended up using:
$('.comp-row [name*="credit_"]:not([type=hidden])')
.each(function(index,elem)
{
console.log($(this).text() != '' ? $(this).find('option:selected').text().trim() : $(this).val());
});
}
Youre looking for the $('select[name*="credit_"]>option:selected') selector.
To read the text value for your , issue .text()
Combine this with if($('input[name*="credit_"]').text() != '') evaluation, combined something like this:
var theName = $('input[name*="credit_"]').text() != ''
? $('select[name*="credit_"]>option:selected').text()
: $('input[name*="credit_"]').text();
Depending on format you want you can use serialize() or serializeArray().
For example to obtain for whole form:
var data=$('#myForm').serialize()
For specific group of elements:
$('[name*=credit_]').serializeArray()
serialize() API docs
serializeArray() API docs
var result = '';
$(this).parent().parent().find('[name*=credit_]').each(function( index ){
result += $(this).is("select") ? $(this).text() : $(this).val();
});
Iterate over all elements that match your criteria (name*=credit_). Check its type and put the value inside a variable.
HTML
<form>
<input type="text" name="credit_a" value="1" />
<input type="text" name="credit_b" value="2" />
<input type="text" name="credit_c" value="3" />
<select name="credit_d">
<option value="kk">kk</option>
<option value="jj" selected>jjjjj</option>
</select>
<input name="credit_e type="checkbox" checked value="imchecked" />
</form>
<form>
<input type="text" name="credit_a" value="55" />
<input type="text" name="credit_b" value="66" />
<input type="text" name="credit_c" value="77" />
<input type="text" name="credit_d" value="88" />
</form>
<p id="result"> </p>
javascript
$(function() {
var values = '';
$('form [name*=credit_]').each(function() {
var $this = $(this);
if($this[0].tagName == 'TEXTAREA') {
values += ' ' + $this.text();
}
else if ($this[0].tagName == 'SELECT') {
values += ' ' + $this.find(':selected').text();
}
else {
values += ' ' + $this.val();
}
});
$('#result').html(values);
});
jsfiddle: http://jsfiddle.net/5tgzr/2/

Jquery Each Input Within DIV (Has A Table)

Im currently trying to get all input elements from a DIV.
$("[required]").each(function() {
});
I have this code which returns every element with a required attribute.
I know within the function of that each() I can use each item like:
$(this)
So I get the div ID's shown below, and try to get all the inputs from it via:
var id = $(this).attr('id');
console.log("### " + id);
console.log($("#" + id + " > :input").length);
Which returns 0 when I have 4 in put elements within that DIV (also theres a table in the div).
What I would ideally like to do is for each input element within my div, print its ID.
UPDATED
<div id="contactAddress" required="true">
<td>Addres line 1:</td>
<td colspan="2">
<input type="text"/>
</td>
<td>Addres line 2:</td>
<td colspan="2">
<input type="text" />
</td>
</tr>
</div>
console.log($(this).html());
Shows nothign but if i add anythign outsire the or like below...
<div id="contactAddress" required="true">
<input type="text" />
And run console.log($(this).html()); It shows it put not the table?
Any ideas im using Jquery Mobile
This below will find all inputs inside the div element. It will then leave a log of the id of this element.
$("div > input").each(function() {
console.log( $(this).attr("id") );
});
if you need the div id containing the inputs you could use .parent()
$("input").each(function() {
console.log( $(this).parent().attr("id") );
});

Categories