Javascript not enabling html forms - javascript

It has been ages i don't work anything in JS, i'm trying to do with a select enable another html form when certain selected option is being chosen. this is my script:
<script>
function Activar() {
var e = document.getElementById('perm_tipo');
var strUser = e.options[e.selectedIndex].text;
if(strUser=="familiar"){
document.getElementById('paciente').disabled = false;
}else{
document.getElementById('paciente').disabled = true;
}
}
i have those html select inside a form, i think that could be the problem but checking on google seems that's should'nt be an issue.
here is my html code:
<form id="registro" action="admin_panel.php" method="post">
<table border="0">
<tr>
<td>Tipo de permiso</td>
<td>
<select name="perm_tipo" onchange="Activar()">
<?php
permiso();
?>
</select>
<br>
</td>
<td>Paciente</td>
<td>
<select id="paciente" disabled>
<?php
pacientes();
?>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Registrar usuario"/><br>
</td>
</tr>
</table>
the php functions just fill the select options with data from some database, no big deal there, they work, no problem there.

Since you are using getElementById, you should use 'id' instead of 'name' in the 'select' element.
<select id="perm_tipo" onchange="Activar()">
....
</select>
More refactor: you can pass the DOM element itself in the event listener and you don't have to do var e = document.getElementById('perm_tipo'); in the first place
<select name="perm_tipo" onchange="Activar(this)">
....
</select>
<script>
function Activar(e) {
var strUser = e.options[e.selectedIndex].text;
if(strUser=="familiar")
document.getElementById('paciente').disabled = false;
else
document.getElementById('paciente').disabled = true;
}
</script>

Related

JavaScript, append HTML and reference IDs in function

I have a form that shows a drop-down menu and a text field next to it:
<html>
<body>
<table>
<tbody class="project_wrapper">
<tr>
<td scope="row">
<select id="test_project" name="test_project[]">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input id="test_value" name="test_value[]" type="text" placeholder="Enter value"></td>
<td><div id="test_calc"></div></td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>
</body>
</html>
You can select one of the values in the drop-down, and when you enter a numeric value into the text field, on each keyup, it'll display the value multiplied by the selected value. You can also click the "Add another project" link and it'll append/create another drop-down and text field. This already works, and is done with the following Jquery code:
<script type="text/javascript">
$(document).ready(function(){
var addProject = $('.add_project');
var wrapper = $('.project_wrapper');
var projectHTML = `<tr>
<td scope="row">
<select id="test_project2" name="test_project[]" class="custom-select">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input id="test_value2" name="test_value[]" type="text" placeholder="Enter value"></td>
<td><div id="test_calc2"></div></td>
</tr>`;
$(addProject).click(function(){
$(wrapper).append(projectHTML);
});
});
$('#test_value').keyup(function(){
$('#test_calc').text(Math.round($(this).val() * $("#test_project option:selected").val()));
});
The problem is I can't get the multiplication function to work/display the result for any newly appended lines. Above you can see I tried hardcoding the values of test_value2 and test_calc2 and then added this below:
$('#test_value2').keyup(function(){
$('#test_calc2').text(Math.round($(this).val() * $("#test_project2 option:selected").val()));
});
I would expect the result (at least for one new appended line) to appear in the same way as for the first line, but nothing seems to happen. My goal is to get the results to appear for the appended line, and then also find a way to have that keyup calculation function work for any number of appended lines (rather than hardcode 2, 3, 4, etc. values).
The ids, I think, will need to be dynamically assigned as the lines are appended, and then the name will stay the same to hold the arrays for test_array and test_value which I'm going to receive and process via PHP.
Thanks!
Remove all your IDs from the template rows, use classes or name="" instead as your selectors
Assign an ID to your TBODY, we'll use it as the .on() event delegator
Use the "input" event, not the "keydown" event. You can also copy/paste values, remember?
on "input" - refer to the parent TR using .closest() before descending back (using .find()) to find the elements specific for that row
Use parseInt() or parseFloat() to handle input strings. Also remember to always fallback to a number i.e: 0 to prevent NaN results
jQuery(function($) {
const projectHTML = `<tr>
<td>
<select name="test_project[]" class="custom-select">
<option value="" selected>Select</option>
<option value="10">10</option>
<option value="20">20</option>
</select>
</td>
<td><input name="test_value[]" type="type" placeholder="Enter value"></td>
<td><div class="result"></div></td>
</tr>`;
const $projects = $("#projects"); // assign an ID to your tbody
const $addProject = $('.add_project');
const arrRow = () => $projects.append(projectHTML);
// Create new row on click
$addProject.on("click", arrRow);
// Add the first row
arrRow();
// use a delegator which is not dymanic (the TBODY in this case),
// and use delegated events to any ":input" element:
$projects.on("input", ":input", function(ev) {
const $tr = $(this).closest("tr");
const $project = $tr.find('[name="test_project[]"]');
const $value = $tr.find('[name="test_value[]"]');
const $result = $tr.find(".result");
const project = parseInt($project.val(), 10) || 0;
const value = parseFloat($value.val()) || 0;
const result = project * value;
$result.text(result);
});
});
<table>
<tbody id="projects"></tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
The IDs must be unique, instead whenever you add another row you duplicate the IDs.
Instead of IDs I changed them to class in order to combine this keyword with .closest() and .find() to get the values of interest.
Moreover, because you add new elements to the table you need to delegate the event.
If you change the select you need to calculate again, not only on typing into the input field.
var addProject = $('.add_project');
var wrapper = $('.project_wrapper');
var projectHTML = '<tr>\
<td scope="row">\
<select class="test_project" name="test_project[]" class="custom-select">\
<option selected>Select</option>\
<option>10</option>\
<option>20</option>\
</select>\
</td>\
<td><input class="test_value" name="test_value[]" type="number" placeholder="Enter value"></td>\
<td><div class="test_calc"></div></td>\
</tr>';
$(addProject).click(function () {
$(wrapper).append(projectHTML);
});
$(document).on('input', '.test_value', function (e) {
$(this).closest('tr').find('.test_calc').text(Math.round($(this).val() * $(this).closest('tr').find('.test_project option:selected').val() || 0));
});
$(document).on('change', '.test_project', function(e) {
$(this).closest('tr').find('.test_value').trigger('input');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody class="project_wrapper">
<tr>
<td scope="row">
<select class="test_project" name="test_project[]">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input class="test_value" name="test_value[]" type="number" placeholder="Enter value"></td>
<td>
<div class="test_calc"></div>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>

replace input type select multiple by some kind of list to force selected elements

I'm trying to achieve something like on this screenshot :
screen
it's basically a form in PHP/Html, and working nicely.
however it's not exactly what I want to do.
I want to take elements from the left and put them to the right side, and get the form validated with the right side elements.
atm, everything works nicely, but my problem is : all elements on the right side need to be "selected" before submitting the form.
is there a way of doing this without having the elements on the right side being "selected".
technically, I just want the "pushed elements" to the right side to be all selected by default in the form.
I suppose my problem comes from the fact that I'm using select instead of another kind of input (can I use a textarea, or some kind of other input ?)
thanks
FYI, here is my source code for this
javascript
<script type="text/javascript" language="Javascript">
function move(sens) {
var i, sourceSel, targetSel;
if (sens == 'right') {
sourceSel = document.getElementById('selectBoxOne');
targetSel = document.getElementById('selectBoxSecond');
} else {
sourceSel = document.getElementById('selectBoxSecond');
targetSel = document.getElementById('selectBoxOne');
}
i = sourceSel.options.length;
while (i--) {
if (sourceSel.options[i].selected) {
targetSel.appendChild(sourceSel.options[i]);
}
}
}
</script>
php/html
<tr>
<th>Associated rights</th>
<td>
<table border="0" cellspacing="0" id="table">
<tr>
<td>
Available (unused) rights (pbroles) <br />
<select name="kiki" multiple="multiple" id="selectBoxOne" size="10" style="width: 325px">
<?php
$q_pbroles = '
SELECT
p.name
FROM
firecall_pbroles p
WHERE
p.name not in (
SELECT
p.name
FROM
firecall_pbroles p,
firecall_roles r,
firecall_l_roles l,
firecall_pbroles_types t
WHERE
p.id = l.pbrole_id
AND
r.id = l.role_id
AND
t.id = p.type
AND
r.id = '.$role_id.'
)
;';
$prep = $dbh->prepare($q_pbroles);
$prep->execute();
$arrAll = $prep->fetchAll();
foreach($arrAll as $data)
{
echo '<option id="multiple'.$data['id'].'" value="'.$data['id'].'">'.$data['name'].'</option>';
}
?>
</select>
<br />
Ctrl+Click to select multiple pbroles
</td>
<td>
<input type="button" value="<<" onclick="move('left');"><br />
<input type="button" value=">>" onclick="move('right');">
</td>
<td>
pbroles in this Role<br />
<select name="pbRoles[]" multiple="multiple" id="selectBoxSecond" size="10" style="width: 325px">
<?php
$q_pbroles = '
SELECT
p.id,
p.name,
t.roletype,
t.descr
FROM
firecall_pbroles p,
firecall_roles r,
firecall_l_roles l,
firecall_pbroles_types t
WHERE
p.id = l.pbrole_id
AND
r.id = l.role_id
AND
t.id = p.type
AND
r.id = '.$role_id.'
ORDER BY
p.type;
';
$prep = $dbh->prepare($q_pbroles);
$prep->execute();
$arrAll = $prep->fetchAll();
foreach($arrAll as $data)
{
echo '<option id="multiple'.$data['id'].'" value="'.$data['id'].'" selected>'.$data['name'].'</option>';
}
?>
</select>
<br />
Ctrl+Click to select multiple pbroles
</td>
</tr>
</table>
</td>
</tr>
There are several ways to achieve this.
See Paul Dixon's answer on "how to pass array through hidden field"
You can add an event listener to the form submit event and then add each selectBoxSecond option to a hidden field inside your form like this:
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function(e) {
var elements = document.getElementsByClassName('hidden_pbRoles');
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
var sourceSel = document.getElementById('selectBoxSecond');
i = sourceSel.options.length;
while (i--) {
var input_hidden = document.createElement("input");
input_hidden.setAttribute('name', 'pbRoles[]');
input_hidden.setAttribute('type', 'hidden');
input_hidden.setAttribute('value', sourceSel.options[i].text);
form.appendChild(input_hidden);
}
};
Now you can also remove name and multiple="multiple" from the second select selectBoxOne:
<select id="selectBoxSecond" size="10" style="width: 325px">
</select>
You can check my working example here: http://zikro.gr/dbg/html/listpost.php
Just move some options from the left to the right select box and then hit submit button to see the POST data result after the page refresh.

JSP giving NullPointerException for request.getParameter()

I'm new to jsp and am creating a webpage that has a form with a select box and a few other input boxes.
I'm populating these input boxes automatically with values from properties file:
NumConfig.properties
SELECT= , ,
ONE=1,I,FIRST
TWO=2,II,SECOND
THREE=3,III,THIRD
Here is my form:
<html>
<body>
<form name="NumDetail" id="NumDetail" method="post">
<div>
<table>
<tr>
<th rowspan="2">Select
<select id="SelectText" name="SelectText" onchange="this.form.submit()">
<option value="ONE">ONE</option>
<option value="TWO">TWO</option>
<option value="THREE">THREE</option>
</select>
</th>
<th align="center">Number</th>
<th align="center">Roman</th>
<th align="center">Position</th>
</tr>
<tr>
<td align="center">
<input type="text" size=10 id="number">
</td>
<td align="center">
<input type="text" id="roman">
</td>
<td align="center">
<input type="text" id="position">
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
And this is the JS code I'm using to load values from properties file:
< script type = "text/javascript" >
<%
ResourceBundle resource = ResourceBundle.getBundle("NumConfig");
String dbname;
if (request.getParameter("SelectText") == null)
dbname = "SELECT";
dbname = request.getParameter("SelectText");
String[] num = resource.getString(dbname).split(","); %>
var number = "<%= num[0]%>";
var rom = "<%= num[1]%>";
var pos = "<%= num[2]%>";
document.getElementById("number").value = number;
document.getElementById("roman").value = rom;
document.getElementById("position").value = pos; < /script>
I can indirectly open this page by appending ?SelectText value in the URL.
But when opening this page directly I get NullPointerException at the line
String[] num = resource.getString(dbname).split(",");
Two Questions:
How do I perform a null check or give the request parameter a default value so that page does not error out?
Once I select a value from the dropdown and the form submits, the select box does not retain its value and goes back to the default. How to resolve this?
You just need an else statement
if (request.getParameter("SelectText") == null)
dbname = "SELECT";
else
dbname = request.getParameter("SelectText");
To make an option selected by default, you should try this selected="selected". Stock the value somewhere and change your selected option dynamically.
<option value="ONE" selected="selected">ONE</option>
Firstly my recommendation would be not to mix Java code within HTML code in a JSP page. Try using a Java Servlet to manage your request and respose so you don't end up having a messy code.
I'll answer your questions below:
You are checking whether the parameter "SelectText" is null, and if that's the case then giving to 'dbname' a default value but the next instruction is replacing this given value with null.
The code should look like this:
String dbname = "SELECT";
String requestValue = request.getParameter("SelectText");
if (requestValue != null) {
dbname = requestValue;
}
Have you tried replacing your form request method with GET instead of POST?

How to insert autocomplete jquery in innerhtml generated textbox

The autocomplete jquery shows list of all users in the database, when atleast 2 characters are entered in the textbox. The autocomplete is working on a normal input field, but when genereated through innerHTML it is not working.
The autocomplete is working on the following field:-
<input type="text" id="j_d_permit_by[]" name="j_d_permit_by[]" >
A click on the button will add other fields as well calling the addjobdesc function:-
<img src="images/add.png" width="12" height="12"> Add New Job Description<br />
The function:-
function addjobdesc() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<table id="tblObs" name="tblObs" width="70%" bgcolor="#CCCCCC"><tr bordercolor="#FFFFFF">
<td colspan="5"><b>Job Description (Work Ppermit/ Activity)</b></td></tr>
<tr bgcolor="#33CC00">
<td ><center> <b>Exact Location</b> </center></td> <td><b><center>Permit Initiated By<br />/<br />Activity Supervised by</center></b></td>
<td><b><center>Permit Accepted By<br />/<br />aActivity Executor</center></b></td><td><b><center>For What Permit Issued</center></b></td>
<td><b><center>Observation</center></b></td></tr>
<tr><td><center><select name="s_area[]" id="s_area" onchange="addSubArea()">
<option value="0">Chose Sub Area</option></select></center></td>
<td><input type="text" id="j_d_permit_by_add" name="j_d_permit_by[]"></td>
<td><center><select id="j_d_accept_by[]" name="j_d_accept_by[]" ><option value="0">Select User</option><?php $users = getUserS();
while($usersss = mysql_fetch_array($users)){ ?>
<option value="<?php echo $usersss[0];?>"><?php echo $usersss[4]." ".$usersss[5]; ?></option>
<?php } ?>
</select></td>
<td><center><textarea name="permit_ref[]" cols="30"> </textarea></center></td>
<td><center><textarea name="obs_permit[]" id="obs_permit" cols="30"></textarea></center></td></tr></table><input class="submit" type="button" value="Remove" onclick="removeR0ow__(this)">';
<!--<input type="hidden" name="j_d_Location[]" id="j_d_Location" value="" /><input type="text" name="area_Location[]" id="area_Location" value="" readonly="readonly" />-->
document.getElementById('job_desc').appendChild(div);
jQuery(document).ready(function(){
$('#j_d_permit_by_add').autocomplete({
source: 'suggest_name.php',
minLength:2
});
});
var Max_Length = parseInt(document.getElementsByName('s_area[]').length)-1;
document.getElementsByName('s_area[]').item(Max_Length).innerHTML = '';
document.getElementsByName('s_area[]').item(Max_Length).innerHTML = document.getElementById('sarea_div').innerHTML;
}
I want the autcomplete to work on the generated j_d_permit_by[] field in the innerHTML.
Really appreciate your help.
You have bind the autocomplete in jQuery(document).ready but at that time there is no input exists with id =j_d_permit_by_add and hence the function is not bind to the input. You are generating the input dynamically so you have to bind autocomplete function in following way..
Try this to Bind the autocomplete function:
jQuery(document).ready(function(){
$(document).on('#j_d_permit_by_add', selector, function() {
$(this).autocomplete({
source: 'suggest_name.php',
minLength:2
});
});
});
You can refer https://stackoverflow.com/a/25114244/1659563
#Guruprasad is also right, you can bind the autocomplete function after the input is generated dynamically in function addjobdesc()

Change value of select option using Js without page refresh

So I want to change the select option using javascript but without reloading the page.
I am able to change other element data using document.getElementById.value
but not the select element
This is what I am trying to do: there is a form and a table inside my webpage , the table data is fetched dynamically using php. The form will edit the data. so when the edit button is pressed the row data against it will be automatically filled into the form.
All other elements of the form could fetch the data with my code. except the select option input element.
below is the the code I have used for each element of the form
jsfiddle here:http://jsfiddle.net/ZE6BX/11/
document.getElementById("l_type").value = data[1];
data array contains the values of the row against which edit is pressed!
u can check whether using index value or option value.
var opt = ocument.getElementById('l_type').options;
for(var i=1;i<opt.length;i++){
if(opt[i].value == 'Ve'){
**opt[i].selected = true;** }
}
this will help u.
This works http://jsfiddle.net/ZE6BX/12/
YOu had a difference in case in between VE in the table and Ve as the value in the select.
Here's the code
HTML:
<div id="l-form">
<form method="post" class="DA_custom_form" id="l-form" action="php/add.php">
<h3>Add</h3>
<label>Name</label>
<input type="text" class="field" id="l_name" name="l_name" />
<label>City</label>
<input type="text" class="field" id="l_city" name="l_city" />
<label>Phone</label>
<input type="text" class="field" id="l_phone" name="l_phone" />
<label>OP</label>
<div class="cl"> </div>
<input type="text" class="field" id="l_op" name="l_op" />
<label>Type</label>
<select class="select_field" id="l_type" name="l_type">
<option value=" ">Select type</option>
<option value="cu">Cu</option>
<option value="Ve">Ve</option>
<option value="Ex">Ex</option>
</select>
<div class="cl"> </div>
<div class="btnp">
<input type="submit" value="Save" name="submit" id="submit" />
</div>
</div>
</form>
</br>
</br>
<table id="existing" border=1>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>View/Edit</th>
</tr>
</thead>
<tbody>
<tr style:padding-left:10px;>
<td>sweet_name</td>
<td>Ve</td>
<td style="display:none">dream_city</td>
<td style="display:none">123456</td>
<td style="display:none">SWAG</td>
<td>
<button class="edit_button" value="Edit" name="button">Edit</button>
</td>
</tr>
</tbody>
</table>
JS:
$(document).ready(function () {
var data;
$("#existing").on("click", ".edit_button", function () {
data = $(this).closest("td").siblings().map(function () {
return $(this).text();
}).toArray();
console.log(data[0]); // name
console.log(data[1]); //type
console.log(data[2]); //city
console.log(data[3]); //phone
console.log(data[4]); //op
document.getElementById("l_name").value = data[0];
$("#l_type").value = data[1];
document.getElementById("l_city").value = data[2];
document.getElementById("l_phone").value = data[3];
document.getElementById("l_op").value = data[4];
});
});

Categories

Resources