This is my first time posting and I just started learning how to code js.
So basically, what I want to know is how do I show or hide content based on the item the user picks from a drop down list.
Here's the php code:
<script src="js/category.js"></script>
<?php
include 'dbh.php';
$sqli='SELECT * FROM categories';
$getdata=mysqli_query($conn,$sqli);
echo "
<form action='category_input.php' method='POST' id='categoryform'>
Category: <select name='category_id'>";
while($row = mysqli_fetch_assoc($getdata))
{
echo
'<option value='.$row['id'].'>'.$row['category_name'].'</option>';
};
echo '</select></form>';
echo "
<div style='display:none;' id='computer'>
<br><br>
Part Number:
<input type='text' style='width:200px' name='part_number' placeholder='Serial Number'>
<br><br>
Serial Number:
<input type='text' style='width:200px' name='serial_number' placeholder='Serial Number'>
<br><br>
<label>Description</label>
<textarea rows='4' cols='50' name='description' form='categoryform'>
</textarea>
<br><br>
</div>
";
echo "
<div style='display:none;' id='peripheral'>
<br><br>
Brand:
<input type='text' style='width:200px' name='brand' placeholder='Brand'>
<br><br>
Type:
<input type='text' style='width:200px' name='type' placeholder='Type'>
<br><br>
Type:
<input type='text' style='width:200px' name='type' placeholder='Type'>
<br><br>
Part Number:
<input type='text' style='width:200px' name='part_number' placeholder='Part Number'>
<br><br>
Serial Number:
<input type='text' style='width:200px' name='serial_number' placeholder='Serial Number'>
<br><br>
</div>";
Here's the category.js code:
var selectedVal = document.getElementsByName("category_id").value;
if(selectedVal == '1') // Put any condition here selectedVal == '1'
{
var element = document.getElementById('computer');
element.style.visibility = 'hidden'; // Hide
}
else
{
var element = document.getElementById('computer');
element.style.visibility = 'visible'; // Show
}
Here's the category_name list:
PC
Notebook
Server
Scanner
Printer
DVD
AccessPoint/Wireless
Mikrotik
Fingerprint
Monitor
Rack Server
DVR
FotoCopy
TV
Modem
Camera
External Storage
ThinClient
Projector
STB BOX(Indihome TV)
VOIP
UPS
Switch
Keyboard
Mouse
I tried to check if it works when I click on category_id = 1 but it doesn't echo the div id="computer"
Sorry for the long post and please tell me if I need to add more information and feedback on how I should do future posts.
Edit: added js
Try this:
var selectedVal = document.getElementsByName("category_id").value;
if(selectedVal == '1') // Put any condition here selectedVal == '1'
{
var element = document.getElementById('id');
element.style.visibility = 'hidden'; // Hide
}
else
{
var element = document.getElementById('id');
element.style.visibility = 'visible'; // Show
}
UPDATE
So I found a working solution:
<script>
function populateField() {
selectedVal = document.getElementById('select').value;
if((selectedVal == '1') || (selectedVal == '2') || (selectedVal == '3'))
{
$("#computer").show();
$("#peripheral").hide();
}
else
{
$("#computer").hide();
$("#peripheral").show();
}
}
And using this:
<select style='width:100%;' name='category_name' id='select' onchange='populateField()'>
Related
I am doing something to prevent user from submitting HTML Form without leaving their remarks for False Hits.
Conditions:
Only if False Hit radio button is selected
The remarks text field cannot be empty (Compulsory)
Currently, I have used JavaScript to check if the text field (Remarks) is empty.
function empty() {
var x;
x = document.getElementById("roll-input").value;
if (x == "") {
alert("Please enter remarks for false hits selected.");
return false;
};
I am also able to check which radio button is selected with JavaScript.
<input type="radio" name="select" id="truehit" value="true" />
<input type="radio" name="select" id="falsehit" value="false" />
if(document.getElementById('falsehit').checked) {
//False Hit radio button is checked
}
else if(document.getElementById('truehit').checked) {
//True Hit radio button is checked
}
However, I am quite stuck at linking both conditions together. Is there a simpler method to this? Any help is greatly appreciated. Thank you in advance.
This is how my Form looks like.
<body bgcolor="#FFFFFF">
<br />
<div align="center" class="h1">
<h1>Entity Search</h1><br />
</div>
</html>
<br />
<?php
include("db_connect.php"); //connect to database
#$loginid = strtoupper(base64_decode($_POST['LanID'])); //to capture
the user's LanID as the UserID
if($loginid == "")
{
$userID = $_SESSION['loginid'];
}
else
{
$_SESSION['loginid'] = $loginid;
$userID = $_SESSION['loginid'];
}
$userID = $_SESSION['loginid'];
//to insert date and time of the records
date_default_timezone_set('Asia/Singapore');
$Date = date('Y-m-d');
$Time = date ('h:i:s a');
$userID = $_SESSION['loginid'];
$loginid = "";
$entityfromform = $_GET["entity"];
?>
<br />
<?php
//connection to database
$connectionInfo = array( "Database"=>"test","UID"=>$test,"PWD"=>$test);
$db_connect=sqlsrv_connect($serverName, $connectionInfo);
//to retrieve the department name from the user database and insert
department name of the user into the records
$namesql = "SELECT Name, DeptName, Role FROM RPDB.dbo.Userdb WHERE
LanID='$userID';";
$name_query = sqlsrv_query($db_connect,$namesql);
while($row = sqlsrv_fetch_array($name_query, SQLSRV_FETCH_ASSOC))
{
$nameontop = iconv("gb2312","UTF-8",$row['Name']);
$admincheck = iconv("gb2312","UTF-8",$row["Role"]);
$deptnamecheck = iconv("gb2312","UTF-8",$row["DeptName"]);
}
$negative = "Negative Hit: No results found.<br />";
$result = "$entityfromform <br />Negative Hit: No results found.<br />";
//variable to insert into the table as result
//search for keyword from form in the Entity Table List where Name =
keyword
$entitysql = "SELECT * FROM RPDB.dbo.entitysearch_table WHERE Name LIKE
'%" . $entityfromform . "%' OR Name = '".$entityfromform."'";
$entity_query = sqlsrv_query($db_connect,$entitysql);
//variables
$i=0;
while($row = sqlsrv_fetch_array($entity_query, SQLSRV_FETCH_ASSOC))
{
$name[$i] = $row["Name"];
$brn[$i] = $row["Business_Registration_Number"];
$address[$i] = $row["Registered_Address"];
$group[$i] = $row["Applicable_Limb_of_Related_Party_Group"];
$selectradio[$i] = 'selectradio'.$i;
$text[$i] = 'text'.$i;
$i++;
}
if(#$name != NULL) //Positive Result
{
echo "<input type='button' name=uncheck' value='Uncheck All'
class='uncheck' onClick='window.location.reload()'>"; //uncheck all
function where it clears all changes
echo "<h2><div align='center'>Results found for:
$entityfromform</div></h2><br />";
//table to display the data
echo "<div align='center'>
<table>
<tr>
<th>Name</th>
<th>Business Registration Number</th>
<th>Registered Address</th>
<th>Applicable Limb of Related Party Group</th>
<th>True Hit</th>
<th>False Hit</th>
<th>Unable To Ascertain</th>
<th>Remarks, for false hit</th>
</tr>
</div>";
echo "<strong><div class='wording'>Positive Hit: </div></strong>";
echo "<br /><br />";
$x=0;
?>
<!--The form data is sent for processing to action_handler.php by HTTP POST method-->
<form method="post" id="form" action="action_handler.php" enctype="multipart/form-data">
<?php
//data displayed in tables along with checkboxes for true hit, false hit, unable to ascertain and text box for remarks where applicable
for($x=0;$x<$i;$x++)
{
echo "<tr>
<td>" . $name[$x] . "</td>
<td>". $brn[$x] . "</td>
<td>". $address[$x] . "</td>
<td>". $group[$x] . "</td>
<td>
<label class='container'>
<input type='radio' id='truehit' name='".$selectradio[$x]."' value='true hit' class='btn' required>
<span class='checkmark'></span>
</label>
</td>
<td>
<label class='container'>
<input type='radio' id='falsehit' name='".$selectradio[$x]."' value='false hit' class='btn'>
<span class='checkmark'></span>
</label>
</td>
<td>
<label class='container'>
<input type='radio' id='unabletoascertain' name='".$selectradio[$x]."' value='unabletoascertain' class='btn'>
<span class='checkmark'></span>
</label>
</td>
<td>
<label><input type='text' name='".$text[$x]."'>
</label>
</td>
</tr>" ;
}
echo "</table>"; //table closed
echo "<br /><br /><br />";
echo "<input type='button' value='Submit' class='submit' onClick='empty()'>"; //submit button to confirm
?>
</form>
<?php
//sessions to be used in others
$_SESSION['num'] = $x;
$_SESSION['entityfromform'] = $entityfromform;
}
else
{
echo "<div align='center'><h2>Results found for: $entityfromform</h2>
<br />";
echo "<div class='wording' align='center'>$negative</div><br><br>
<br>";
}
?>
</table>
</body>
your empty() function does not return anything if the textbox has a value and hence for that condition it is undefined; you can create a function for your requirement like:
function doSubmit()
{
if(document.getElementById('falsehit').checked)
{
if(document.getElementById("roll-input").value == '')
{
alert("Please enter remarks for false hits selected.");
return false;
}
}
return true;
}
and call this method to validate, so if falsehit is checked and remarks has a value it'll return true or else false.
Hope this helps; let me know if I'm missing to understand your problem here..
Happy coding...
You can use a set of if statements like below. This basically checks if the falsehit radio button is checked. If it is, then it checks if the text is empty. If the text is empty, it alerts what you wanted it to. If the text isn't empty, it submit's the form.
Also, if falsehit is not checked, it automatically submit's the form.
As per request in the comments: Now I get every radio button, and loop through them to check if they're selected. If they aren't, you get an alert message saying Please select all accordingly. Otherwise, it just works the same as before.
function empty() {
var text;
var groups = document.querySelectorAll("[id^=group]");
var selected = {};
var radioButtons;
var submitForm = true;
groups.forEach(e1 => {
radioButtons = e1.querySelectorAll("input[type=radio]");
radioButtons.forEach(e2 => {
if (e2.checked) {
selected[e1.id] = true;
}
});
if (selected[e1.id] == undefined) {
selected[e1.id] = false;
}
});
groups.forEach(e => {
text = e.children[0].value;
for (var i = 0; i < e.children.length; i++) {
if (e.children[i].id == "falsehit") {
if (e.children[i].checked) {
if (text.length == 0) {
alert("Please enter remarks for false hits selected.");
submitForm = false;
}
} else if (selected[e.id]) {
//Don't need to do anything. Just need to prevent the next else from accessing these values
} else {
alert("Please select all accordingly.");
submitForm = false;
}
}
}
});
if (submitForm) {
document.getElementById("form").submit();
}
}
<form id="form">
<fieldset id="group1">
<input type="text" id="roll-input" />
<input type="radio" name="group1" id="truehit" value="true" />
<input type="radio" name="group1" id="falsehit" value="false" />
</fieldset>
<fieldset id="group2">
<input type="text" id="roll-input" />
<input type="radio" name="group2" id="truehit" value="true" />
<input type="radio" name="group2" id="falsehit" value="false" />
</fieldset>
<input type="button" value="Submit" onclick="empty()" />
</form>
I want to disable all the user input fields in a form, if the 'Status Active' checkbox is unchecked. The target is to load the page with all the details but if the Status is not active then the checkbox will show as unchecked and the rest of the input fields will remain disabled, till the user checks the checkbox. He can then edit the data and save it.
However, if the record is active, then all the fields will be enabled for editing straight away.
I have already achieved this, but the only problem is even when the record is active, the input fields are getting disabled. Can anyone please point out where is the error in my code?
<script type='text/javascript'>
$(function(){
if($('#square').not(':checked')){
$('#prizename, #prizedesc, #comment').attr('disabled','disabled');
}
});
function checkDisable(){
var square = document.getElementById('square');
var prizename = document.getElementById('prizename');
var prizedesc = document.getElementById('prizedesc');
var comment = document.getElementById('comment');
if(square.checked){
prizename.disabled = false;
prizedesc.disabled = false;
comment.disabled = false;
}
if(!square.checked ){
prizename.disabled = true;
prizedesc.disabled = true;
comment.disabled = true;
}
}
</script>
<php codes here>
<div>
<table>
<tr>
<td>Prize Status - Active:</td>
<td><div class="square">
<input type="checkbox" name="status" id="square" value="1" onchange="checkDisable()" <?php if ($status == 1) echo 'checked'; ?> />
</div>
</td>
</tr>
</table>
<label>Prize Name <input type="text" name="prizename" id="prizename" value="<?php echo isset($_POST['prize']) ? $prizename : '' ?>" > </label>
<label>Prize Description <input type="text" name="prizedesc" id="prizedesc" value="<?php echo isset($_POST['prize']) ? $prize_description : '' ?>" > </label>
<label>Comment <textarea name="comment" id="comment" rows="4" ><?php echo $comment ?> </textarea> </label>
</div>
<div class="button-section">
<input id="save_button" type="submit" name="submit" value="Save">
</div>
$('#square').not(':checked')
this condition is not satisfied because it will return the object. You have to check with length. Please check in your code.
if($('#square').not(':checked').length > 0)
Or
if(!$('#square').is(":checked"))
I have altered your code - Working from my side.
HTML: (Just insert your variables again)
<table>
<tr>
<td>Prize Status - Active:</td>
<td>
<div class="square">
<input type="checkbox" name="status" id="square" value="1">
</div>
</td>
</tr>
</table>
<label>Prize Name <br><br><input type="text" name="prizename" id="prizename"
value="Juan" ></label>
<label>Prize Description <input type="text" name="prizedesc" id="prizedesc"
value="Description" ></label>
<label>Comment <textarea name="comment" id="comment" rows="4"
>Comment</textarea></label>
<div class="button-section">
<input id="save_button" type="submit" name="submit" value="Save">
</div>
JS: (The first bit executes on page load and the second part is listening for the change event on the checkbox)
if($('#square').not(':checked').length > 0){
document.getElementById('prizename').disabled = true;
document.getElementById('prizedesc').disabled = true;
document.getElementById('comment').disabled = true;
} else {
document.getElementById('prizename').disabled = false;
document.getElementById('prizedesc').disabled = false;
document.getElementById('comment').disabled = false;
}
const checkbox = document.getElementById('square');
checkbox.addEventListener('change', (event) => {
if (event.target.checked) {
document.getElementById('prizename').disabled = false;
document.getElementById('prizedesc').disabled = false;
document.getElementById('comment').disabled = false;
} else {
document.getElementById('prizename').disabled = true;
document.getElementById('prizedesc').disabled = true;
document.getElementById('comment').disabled = true;
}
})
I am really stuck.
All i want to do is save a form not just the data into a session, the actual form. The idea is the administrator can add as many extra's to a product. My problem is i cannot work out how to save the form into a session (current code not working). I just cannot get my head around it. I am a newbie so i am getting rather confused.
At the moment i have the dynamic form but the form and data disappear on page refresh.
I have created the dynamic form:
var counter = 1;
var limit = 50; // the amount of addons that are allowed
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><label id='cat_label' name='cat_label' class='lab'>Name</label>\n\
<input type='text' id='cat_name' name='cat_name' value=''>\n\
<br>\n\
<label id='desc_label' name='desc_label' class='lab'>Description</label>\n\
<input type='text' id='cat_desc' name='cat_desc' value=''>\n\
<br>\n\
<hr id='dotted'>\n\
<br>\n\
<p id='menu_head'> Menu Item</p>\n\
<input type='button' value='Add New item to ...' onClick='addInput('new item');'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
<div id="dynamicInput">
<br><!--<input type="text" name="myInputs[]">-->
<label id="cat_label" class="lab">Name</label>
<input type="text" id="cat_name" name="cat_name[]" value="<?php print $_SESSION['form']['cat_name'][$counter]; ?>">
<br>
<label id="desc_label" class="lab">Description</label>
<input type="text" id="cat_desc" name="cat_desc[]" value="<?php print $_SESSION['form]['cat_desc'][$counter]; ?>">
</div>
<input type="button" value="Add" onClick="addInput('dynamicInput');">
<input type="submit" id="submit" name="submit" value="Save...">
</form>
I started this:
if (count($_POST) > 2 && $_POST['submit'] == "Save...") {
$countNumberOfInputs = count($_POST['cat_name']);
foreach($_POST as $key=>$value) {
if(!is_array($value)) {
$value = strip_tags($value);
$value = preg_replace("/[^0-9a-z -,.!]/i", "", $value);
}
$_SESSION['form'][$key] = $value;//save to session
}
if ($countNumberOfInputs < 1 ) {
$countNumberOfInputs = 1;
$counter = 0;
}
How can i resolve this, even better could someone highlight where i went wrong?
I'm trying to make 3 form fields (a dropdown list dynamically populated by a .php script and 2 text fields) and also with a button add 3 more and 3 more and so on (as user clicks the button) I have tried several ways but nothing seems to work for me. (I'm noob in JS, AJAX, jQuery so I mostly tried scripts I've found on the internet).
Here's the code of these form fields:
<form id="form1" name="form1" method="post" action="results.php">
<div id="itemRows">
<select name="species">
<option value="">Select Species</option>';
<?php $sql = "SELECT common FROM species";
$speciesq = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($speciesq))
{
echo "<option value=\"" . $row['common'] ."\">" . $row['common'] ."</option>";
}
?>
</select>
Number: <input type="text" name="speciesnumber1" size="7" /> Weight: <input type="text" name="speciesweight1" /> <input onClick="addRow(this.form);" type="button" value="+" />
</div></form>
and after this form there's the code:
<script type="text/javascript">
var rowNum = 0;
var ddsel = '<select name="species'+rowNum+'>';
var ddopt = '<option value="">Select Species</option>';
var ddselc= '</select>';
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
}, "json");
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
getlist.php is a simple script that populates the dropdown list and sends the data:
<?php
include("dbcon.php");
$sql = mysqli_query ($con, "SELECT common FROM species");
$result = array();
while ($row = mysqli_fetch_array($sql)){
$result[] = array(
'value' => $row['common'],
);
}
echo json_encode($result);
?>
So when I click the "+" button (to add the row) nothing happens.
SOLVED: for those who come here please read also the comments below the answer.
You just have some code in the wrong spot:
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
needs to be moved into the post return function like this:
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
var frm = document.getElementById('form1');
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}, "json");
}
I have a query regarding form generation based on current inputs,
like in applications the text input appear based on our choice.
I am trying to make it work using JavaScript , but my code doesn't do anything:
<html>
<head>
<script>
function addInput() {
if (fields != 10) {
document.getElementById('d_div').innerHTML += "<input type='text' value='' /><br />";
fields += 1;
} else {
document.getElementById('d_div').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}}
</script>
</head>
<body>
<div align = "center">
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
Select a Template<br />
<select name = "template" id = "rawquery">
<option>Select</option>
<option value = "Alpha query">Alpha</option>
<option value = "Betaquery">Beta</option>
<option value = "Gamma query">Gamma</option>
<option value = "Epsilon query">Epsilon</option>
</select>
<br/>
<input type = "submit" name = "submit"><br /><br />
</form>
</div>
<textarea name = "raw" rows = "10" cols = "50" id = "Raw">raw template</textarea>
<br /><br />
<form id="d_form">
<input type="submit" onclick="addInput()" name="newform" value="Click to enter values">
</form>
<div id="d_div"> </div>
</div>
<br> <br> <br> <br>
</body>
</html>
The code making drop-down menu is not used here.
When I click on the button to enter values it doesn't give me a new text area; can you please help, I am very new to this and learning?
where is 'fields'-initialization?
don't forget returning false, if really don't need to submit form #d_form clicking button #newform
You have a lot of problems with your tags. First make those right. I am giving an example
of creating dynamic tags. I think you can use it.copy and see how it works
<script type="text/javascript">
fields=0;
function addInput() {
textvalue=document.getElementById("raw").value;
var opt = document.createElement("option");
if (fields != 10) {
opt.text=textvalue;
document.getElementById('rawquery').options.add(opt);
fields += 1;
} else {
document.getElementById('d_div').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled = true;
}
}
</script>