I'm currently trying to find a way to fill the max value of an input according to the
max="#value"
Currently I'm using asp.net mvc, I'm getting data from a datatable and I render this information inside a html table where in my tr> /tr> I have a td> /td> that looks like this
<td align="center"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" min="0" max="#monto.Trim()" value="" step="any" style="width: 100px" /></td>1
Can anyone tell me how to make a javascript function that automatically fills the max="" value inside a Html TableRow?
The problem is that each row has its unique max #value
Assume the following HTML:
<td align="center">
<input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" min="0" max="#monto.Trim()" value="" step="any" style="width: 100px" />
<button class="set-max">Max value</button>
</td>
You can add an event listener on the button via JavaScript e.g. put this code in the bottom of your table or in the bottom of the <body> tag.
<script>
var buttons = document.querySelectorAll('.set-max');
buttons.forEach(function (button) {
button.addEventListener('click', function (event) {
var input = event.currentTarget.parentElement.querySelector('input[type="number"]');
input.value = input.max;
});
};
<script>
If the button ends up somewhere else you'd need to adjust the event listener to find the actual target element by navigating through the DOM hierarchy
Related
I'm writing a form and I have to let the user add as many rows as required.
As you can see, my inputs are treated as arrays to later save the data to the DB. (That will be another new thing to me)
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<tr> <td><input type="text" id="NombreProyecto" name="NombreProyecto[]"></td> <td><input type="text" id="Descripcion" name="Descripcion[]"></td> <td><input type="text" id="AplicacionesProyecto" name="AplicacionesProyecto[]"></td> <td style="width: auto"> <div class="range-field "> <input type="range" name="NivelTRL[]" min="1" value="1" max="9" /> </div> </td> </tr>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="step-content">
<div class="container">
<div id="table" class="table-editable ">
<table class="table field_wrapper">
<tr>
<th>Nombre</th>
<th>Descripción</th>
<th>Aplicaciones</th>
<th>Nivel TRL</th>
<th><i class="material-icons">add</i>
</th>
</tr>
<tr class="">
<td><input type="text" id="NombreProyecto" name="NombreProyecto[]"></td>
<td><input type="text" id="Descripcion" name="Descripcion[]"></td>
<td><input type="text" id="AplicacionesProyecto" name="AplicacionesProyecto[]"></td>
<td>
<div class="range-field">
<input type="range" name="NivelTRL[]" min="1" value="1" max="9" />
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>
Everything looks perfect but when the user adds a new row and interacts with the range input, this won't feedback the user about the value he/she is picking.
Just the original one will have the tooltip.
After some testing, it even affects the 'tooltipped' class used to, well, show tooltips over any element.
This is the codepen, It's all ready to show you the problem
How to reproduce it:
In the codepen provided, you will see the blue cross, when you click on it a new row will be added.
Play around with the first range input, it will show you the value on the tooltip.
In the later added range input, it wont.
Thank you for reading, have a nice day.
You should reinit your range elements.
Simply add this code
M.Range.init($('input[type=range]'));
after this
$(wrapper).append(fieldHTML); //Add field html
First, it's not a tooltip on that range input... It's the Materialize nouiSlider effect. So you have to initialyse this on the new element.
M.Range.init(element);
By the way, I did not found this specific is the documentation about range... But I got inspired by this other initialisation example.
CodePen updated
I'm building a multipage form. On a few of the form's pages, I have questions that allow the user to add inputs dynamically if they need to add a job, or an award, etcetera. Here's what I'd like to do/what I have done so far.
What I Want to Do:
As the user adds fields dynamically, I want to validate those fields to make sure they have been filled in, and they are not just trying to move to the next page of the form with empty inputs.
After all the fields are successfully validated, a "Next" button at the bottom of the page, which up until this point was disabled, will become reenabled.
What I know How To Do
With some help, I've been able to workout a validation pattern for the inputs that are not dynamically added (such as First Name, Last Name) and I can extend this same logic to the first set of inputs that are not added dynamically. I have also worked out how to re-enable the "Next" button once all fields are good.
What I do Not Know How To Do
How do I write a function that extends the logic of the simple validation test to also check for dynamically added iterations.
http://codepen.io/theodore_steiner/pen/gwKAQX
var i = 0;
function addJob()
{
//if(i <= 1)
//{
i++;
var div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" placeholder="School Board" name="schoolBoard_'+i+'"> <input type="text" class="three-lines" placeholder="Position" name="position_'+i+'"> <input type="date" class="three-lines" name="years_'+i+'"> <input type="button" value="-" onclick="removeJob(this)">';
document.getElementById("employmentHistory").appendChild(div);
//}
}
function removeJob(div)
{
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
};
function checkPage2()
{
var schoolBoard_1 = document.getElementById("schoolBoard_1").value;
if(!schoolBoard_1.match(/^[a-zA-Z]*$/))
{
console.log("something is wrong");
}
else
{
console.log("Working");
}
};
<div id="page2-content">
<div class="input-group" id="previousTeachingExperience">
<p class="subtitleDirection">Please list in chronological order, beginning with your most recent, any and all full-time or part-time teaching positions you have held.</p>
<div class="clearFix"></div>
<label id="teachingExpierience">Teaching Experience *</label>
<div id="employmentHistory">
<input type="text" class="three-lines" name="schoolBoard_1" id="schoolBoard_1" placeholder="School Board" onblur="this.placeholder='School Board'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />
<input type="text" class="three-lines" name="position_1" placeholder="Position" onblur="this.placeholder='Position'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />
<input type="date" class="three-lines" name="years_1" />
<input type="button" name="myButton" onclick="addJob()" value="+" />
</div>
</div><!--end of previousTeachingExperience Div -->
Instead of trying to validate each individual input element, I would recommend trying to validate them all at once. I believe that is what your checkPage2 function is doing.
You can add the onBlur event handler or the onKeyUp event handler you are currently using to all added inputs to run your form wide validation. This has the effect of checking each individual form element if it is valid so you know for sure you can enable the submit button.
Lastly, when removeJob is called, you should also run the form wide validation. It would look something like this:
function addJob()
{
i++;
var div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" placeholder="School Board" name="schoolBoard_'+i+'" onkeyup="checkPage2()"> <input type="text" class="three-lines" placeholder="Position" name="position_'+i+'" onkeyup="checkPage2()"> <input type="date" class="three-lines" name="years_'+i+'" onkeyup="checkPage2()"> <input type="button" value="-" onclick="removeJob(this)">';
document.getElementById("employmentHistory").appendChild(div);
}
function removeJob(div)
{
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
checkPage2();
};
For every element that you make with document.createElement(...), you can bind to the onchange event of the input element, and then perform your validation.
Here's an updated version of your CodePen.
For example:
HTML
<div id="container">
</div>
Javascript
var container = document.getElementById("container");
var inputElement = document.createElement("input");
inputElement.type = "text";
inputElement.onchange = function(e){
console.log("Do validation!");
};
container.appendChild(inputElement);
In this case I'm directly creating the input element so I have access to its onchange property, but you can easily also create a wrapping div and append the inputElement to that.
Note: Depending on the freqency in which you want the validation to fire, you could bind to the keyup event instead, which fires every time the user releases a key while typing in the box, IE:
inputElement.addEventListener("keyup", function(e){
console.log("Do validation!");
});
I'm trying to walk through and alter someone else's code (racktables open source application)... and maybe I've been looking at it too long.
But I can't figure out why clicking on the "Edit Row" image/button in the 4th cell below trigger the form to submit.
HTML Code
<tr>
<td id=""><img src="?module=chrome&uri=pix/tango-user-trash-16x16-gray.png" title="1 rack(s) here" height="16" width="16" border="0">
<form method="post" id="updateRow" name="updateRow" action="?module=redirect&page=rackspace&tab=editrows&op=updateRow">
<input tabindex="1" name="row_id" value="26270" type="hidden">
</form>
</td>
<td><div id="location_name"></div></td>
<td><div id="row_name">BLDG5:First Floor</div></td>
<td>
<input tabindex="1" name="edit" class="edit" src="?module=chrome&uri=pix/pencil-icon.png" id="" title="Edit row" type="image" border="0">
<input tabindex="1" style="display: none;" name="submit" class="icon" src="?module=chrome&uri=pix/tango-document-save-16x16.png" title="Save changes" type="image" border="0"></td>
<td>Row BLDG5:First Floor</td>
</tr>
I've added / created the edit button, as well as some jquery code to handle the edit click event.
Jquery Code
//edit button handler
$(".edit").click(function(e){
var location_id = this.id;
var menu = $( "#location_id" ).clone();
//locate the associated "location_name" field for the selected row & hide the column
var location_name=$(this).parent().siblings().children("#location_name").hide();
var row_name = $(this).parent().siblings().children("#row_name").hide();
//replace location_name with the new menu
$(location_name).replaceWith(menu);
menu.find('option').each(function(i, opt) {
// when the value is found, set the 'selected' attribute
if($(opt).attr('value') == location_id.toString()) $(opt).attr('selected', 'selected');
});
//change row name to input box for editing
var input = $(document.createElement('input'));
$(input).attr('type','text');
//$(input).attr('name','edit_row_name');
$(input).attr('value', $(row_name).text());
//replace exiting row_name with this new input box.
$(row_name).replaceWith($(input));
//show save button
var save_btn = $(this).siblings(".icon").show();
});
What I've tried so Far
When i disable / comment out the logic in PHP that creates the form, the edit button works the way i want it to.
I've been grepping the folder structure to see if there's some javascript embedded somewhere that I'm not seeing. But nothing is jumping out at me.
It's probably something really simple that I'm not seeing / recognizing.
Any suggestions?
See:
<input type='image' />
is also have a default action to submit the forms just like [type="submit"]. to prevent it you need to stop the default behavior:
$(".edit").click(function(e){
e.preventDefault(); // <----use this.
In my code, I made a JavaScript function which will delete the current row from a table. Then in HTML I put that function into an 'input' element which will trigger the function in an 'onclick' action. Everything works fine if I make the input type="button", but if I make it type="image" as you can see below, even with "return false;", whenever I press enter in any of the input field in the same row, it will trigger the delete function.
I don't know why.
function deleteRow(r)
{
var rowLength= document.getElementById("newOrder").rows.length; //get how many rows are in this table
if (rowLength == 2) //if there are only two rows (including header), then don't allow to delete a row
{
alert ("At least one row is needed to create an order.");
return;
} else //if row number is greater than 2, then delete a row is allowed
{
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("newOrder").deleteRow(i);
}
following is the HTML code
<tr>
<td class="item"><input type="image" onclick="deleteRow(this); return false;" src="img/delete.png" height="20" width="20" alt="delete"><input type="text" class="biginput, item" ></td>
<td class="detail"><input class="detail" type="number" ></td>
<td class="detail"><input class="detail" type="number" ></td>
</tr>
Use this: Demo Link
<form>
<input id="image" onclick="return deleteRow(this);" type="image" src="img/delete.png" height="20" width="20" alt="delete" />
</form>
Using pure javascript:
function deleteRow(instance) {
alert("delete");
return false;
}
Using jquery as you have tagged jquery in your post:
$('#image').click(function(event) {
event.preventDefault(); // yaa!
alert("delete");
});
I have a fairly long form on a page with various checkboxes and text boxes. There is one point where I want a text box to become available if a corresponding checkbox is ticked. I almost have it working with this code:
<tr class= "formspace">
<td class="formleft" valign="top" style="line-height:22px">Extra bed(s)?</td>
<td colspan="2"><input name="extrabed" type="checkbox" value="1" onChange="jsextrabed()"><?php echo $lang["extraadultx"]." ".$lang["notsingleoccx"];?>
<div id="extrabednumber"></div>
<script type="text/javascript">
function jsextrabed() {
if(document.roomnew.extrabed.checked == 1) {
document.getElementById("extrabednumber").innerHTML=' Max number of extra beds <input name="extrabed" type="text" id="extrabed" size="1" maxlength="1" value="1">';
}else{
document.getElementById("extrabednumber").innerHTML=' Max number of extra beds <input name="extrabed" type="text" id="extrabed" size="1" maxlength="1" value="0">';
}
}
</script>
</td>
</tr>
When the page first opens, only the checkbox shows.
When I tick the checkbox, the text box opens with a value of 1. So far, so good.
When I click again the checkbox is unticked and the value in the text box changes to 0. Still good.
When I click yet again the checkbox is ticked (good) but the value in the text box stays at 0 (bad!).
Further clicking toggles the checkbox but has no effect on the value in the text box.
What have I done wrong?
use this code for check:
if(document.roomnew.extrabed.checked) {
Just check with
if(document.roomnew.extrabed.checked){
}
else
{
}
There is no problem in the displayed code.
Here's a working demonstration : http://jsfiddle.net/dystroy/u6mtW/
HTML :
<tr class= "formspace">
<td class="formleft" valign="top" style="line-height:22px">Extra bed(s)?</td>
<td colspan="2"><input name="extrabed" id=checkextra type="checkbox" value="1" >some php
<div id="extrabednumber"></div>
</td>
</tr>
Javascript :
<script>
window.onload=function(){
document.getElementById('checkextra').onchange = function() {
if(this.checked) {
document.getElementById("extrabednumber").innerHTML=' Max number of extra beds <input name="extrabed" type="text" id="extrabed" size="1" maxlength="1" value="1">';
}else{
document.getElementById("extrabednumber").innerHTML=' Max number of extra beds <input name="extrabed" type="text" id="extrabed" size="1" maxlength="1" value="0">';
}
};
};
</script>
I made a few changes to
adapt to the fact that we don't have the whole DOM. Your problem may be there, in the parts we don't see.
ensure the function is correcly hooked on the checkbox (you may have a problem of not fully loaded DOM, depending on your page)
Problem solved!
I was using the same name for two elements: both the checkbox input and the text box input (in the innerHtml were called "extrabed". Changing one of those has fixed it.
Thanks to all of you who offered help.