show no of fields depending on number selected in dropdown - javascript

I am looking at this post: Using jQuery to dynamically add form fields (or fieldsets) based on a dropdown box value
is there not an easier way?
my code:
<tr>
<td valign="top">
<label for="children">No. of Minor Children*</label>
</td>
<td>
<select id="nochildren" name="nochildren" onchange="displayfields(this.value)">
<option value="1">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<br />
<option value="<?php echo $row_list['nochildren']; ?>">
<?php if($row_list['nochildren']==$select){ echo $row_list['nochildren']; } ?>
</option>
<script language="JavaScript">
$(document).ready(function(){
$('#nochildren').change(function(){
$("#child").show();
displayfields($(this).val());
});
});
function displayfields(val)
{
for (var i=1 ; i<val; val++)
{
alert(i);
$("#child"+i).show();
}
}
</script>
</tr>
<div id="child">
<tr>
<td valign="top">
<label for="names">Child Full names*</label>
</td>
<td valign="top">
<input type="text" name="childname" maxlength="50" size="30"></input>
</td>
</tr>
</div>
if no children don't show the div if 4 children show 4 div tags

Try this:
<script type="text/javascript">
$(document).ready(function(){
$('#nochildren').change(function(){
//-------
// Here add your code to hide all div's
//-------
displayfields($(this).val());
});
});
function displayfields(val)
{
for (var i=1 ; i<val; val++)
{
alert(i);
$("#child"+i).show();
}
}
</script>

See this Fiddle. I have not included the styles for it and it is just a core implementation.
Below is the jQuery which I am using
$(function(){
var inputString="<input type='text'>";
$('#selectBox').on('change',function(){
$('#result').html('');
for(var i = 0;i<$('#selectBox :selected').val();i++)
{
$('#result').append(inputString);
}
});
});

Related

How can I add/remove select boxes from DOM when all select boxes have one name so that upon Submit I get value from active select box?

TL;DR: I want to be able to make a selection using currently-active HTML select box, when I have multiple select boxes with the same name, but only one of them is to be active at any one time.
--
My question is this - I have multiple filename select boxes, that upon submit, always send the value of the last select box that is at the bottom of HTML that has filename name in HTTP Request. I want to find a way to send only the filename that is associated with the currently-active a_XX_row box, and not any others.
i.e. I select id of 40, I should only see the box that says "A-40 Designer and Specs", and not the 800 box. When I press submit I want POST['filename'] to have the "A-40 Designer and Specs", but instead I always get the "A-800 Designer E.xlsm", because it is the last select in the HTML file.
$('#modelid').on('change', function() {
if (this.value == 40)
$('.a_40_row').show();
else
$('.a_40_row').hide();
if (this.value == 800)
$('.a_800_row').show();
else
$('.a_800_row').hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--
<option value="40">40
<option value="800">800
</select>
</td>
</tr>
<tr class="a_40_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option selected>A-40 Designer and Specs B.xlsm</option>
<option>A-40 Designer and Specs A.xlsm</option>
</select>
</td>
</tr>
<tr class="a_800_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option>A-800 Designer E.xlsm</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
don't show/hide selects form.
you just need to update the second select when the first is changed
the way to do that:
const
myForm = document.forms['my-form']
, filenames =
[ { model: '40', cod: 'A-40-B', fn:'A-40 Designer and Specs B.xlsm' }
, { model: '40', cod: 'A-40-A', fn:'A-40 Designer and Specs A.xlsm' }
, { model: '800', cod: 'A-800-E', fn:'A-800 Designer E.xlsm' }
]
myForm.modelid.onchange = () =>
{
myForm.filename.innerHTML = ''
filenames
.filter(x=>x.model===myForm.modelid.value)
.forEach( filename=>
{
myForm.filename.add( new Option(filename.fn,filename.cod))
}
)
}
select,
button {
display : block;
float : left;
clear : left;
margin : .3em;
}
select {
min-width : 8em;
padding : 0 .3em;
}
<form name="my-form">
<select name="modelid" >
<option value="" selected disable >--select--</option>
<option value="40" > 40 </option>
<option value="800" > 800 </option>
</select>
<select name="filename"></select>
<button type="submit">submit</button>
</form>
Two options,
Enable/disable the element as you show it.
Populate one field with what you need.
Option 1 :
$('#modelid').on('change', function() {
//Set visibility
$('.a_40_row').toggle(this.value == 40);
//Toggle disabled
$('.a_40_row [name=filename]').prop("disabled", this.value != 40);
$('.a_800_row').toggle(this.value == 800)
$('.a_800_row [name=filename]').prop("disabled", this.value != 800);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--</option>
<option value="40">40</option>
<option value="800">800</option>
</select>
</td>
</tr>
<tr class="a_40_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename" disabled>
<option selected>A-40 Designer and Specs B.xlsm</option>
<option>A-40 Designer and Specs A.xlsm</option>
</select>
</td>
</tr>
<tr class="a_800_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename" disbled>
<option>A-800 Designer E.xlsm</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
Option 2 : - This uses HTML 5 which has issues in IE 10 and less
$('#modelid').on('change', function() {
$(".row").show();
var selVal = $(this).val();
//Go through the options
$("[name=filename] option").each(function(){
//Dont use jquerys data here, it will convert to a number when it can
//Get array of values where can display from the data attribute
var arrDisplay = this.dataset.display.split(",");
//Add the hidden property if not contained in array -- wont work in IE 10 and older
$(this).prop("hidden", !arrDisplay.includes(selVal));
//Set a default
$(this).prop("selected", $(this).data("optiondefault") && !arrDisplay.includes(selVal) )
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--</option>
<option value="40">40</option>
<option value="800">800</option>
</select>
</td>
</tr>
<tr class="row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option data-display="40" data-optiondefault="true">A-40 Designer and Specs B.xlsm</option>
<option data-display="40">A-40 Designer and Specs A.xlsm</option>
<option data-display="800" data-optiondefault="true">A-800 Designer E.xlsm</option>
<option data-display="40,800">Hybrid</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>

cannot display text onchange select option

I have 1 set of <select><option> which is if I select 1 option by it value, it will display some text in <div>.
This is my code
$(document).ready(function() {
$('#selectcom').change(function() {
opt = $(this).val();
if (opt == "comp_id") {
$('#new_text').html('Varchar');
$('#size_row').html('20');
} else if (opt == "comp_name") {
$('#new_text').html('Varchar');
$('#size_row').html('20');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<select class="selectField" onChange="" id="selectcom">
<option value="">-- Select Field --</option>
<option value="comp_id">comp_id</option>
<option value="comp_name">comp_name</option>
</select>
</td>
<td id="data_row">
<div id="new_text"></div>
</td>
<td id="size_row">
<div id="size_row"></div>
</td>
</tr>
The problem is I cannot display any output either varchar text or 20 text with this code. Anyone please help me. Thank you..
No enough information; yet try to make sure you included jQuery reference in :
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
In case you did that , as I can see from jsfiddle. I suspect the css is showing the output in white...try to show some css code.
First check console if you are getting some error due to other script also remove onChange="" if you are using direct jquery on change function, or use below approach.
<tr>
<td>
<select class="selectField" onChange="changeMyValue(this.value)" id="selectcom">
<option value="">-- Select Field --</option>
<option value="comp_id">comp_id</option>
<option value="comp_name">comp_name</option>
</select>
</td>
<td id="data_row"><div id="new_text"></div></td>
<td id="size_row"><div id="size_row"></div></td>
</tr>
function changeMyValue(opt) {
if (opt=="comp_id")
{
$('#new_text').html('Varchar');
$('#size_row').html('20');
}
else if (opt == "comp_name")
{
$('#new_text').html('Varchar');
$('#size_row').html('20');
}
}
It works. I would suspect that you haven't referenced jQuery before your script block/file. Check the developer's console. Does it display something like:
Uncaught ReferenceError: $ is not defined
Solution: Make sure your jQuery file is loaded before your script block/file.
Like:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="your-jsfile.js" type="text/javascript"></script>
Not like:
<script src="your-jsfile.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).ready(function() {
$('#selectcom').change(function() {
opt = $(this).val();
if (opt == "comp_id") {
$('#new_text').html('Varchar');
$('#size_row').html('20');
} else if (opt == "comp_name") {
$('#new_text').html('Varchar');
$('#size_row').html('20');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<select class="selectField" onChange="" id="selectcom">
<option value="">-- Select Field --</option>
<option value="comp_id">comp_id</option>
<option value="comp_name">comp_name</option>
</select>
</td>
<td id="data_row">
<div id="new_text"></div>
</td>
<td id="size_row">
<div id="size_row"></div>
</td>
</tr>
Also, I recommend using a switch statement. I don't know about performance, but in my opinion, it improves readability.
$(document).ready(function() {
$('#selectcom').change(function() {
opt = $(this).val();
switch (opt) {
case "comp_id":
$('#new_text').html('Varchar');
$('#size_row').html('20');
break;
case "comp_name":
$('#new_text').html('Varchar');
$('#size_row').html('20');
break;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<select class="selectField" onChange="" id="selectcom">
<option value="">-- Select Field --</option>
<option value="comp_id">comp_id</option>
<option value="comp_name">comp_name</option>
</select>
</td>
<td id="data_row">
<div id="new_text"></div>
</td>
<td id="size_row">
<div id="size_row"></div>
</td>
</tr>

Javascript get data attribute from selected option in a table

I got the following html:
<td class="" data-id="46" contenteditable="true">
<select class="form-control">
<option data-key="end" selected>Opt1</option>
<option data-key="operator_transfer">Opt2</option>
<option data-key="process_script">Opt3</option>
</select>
</td>
I need to get data attribute of the selected option. I am trying to do it that way:
var cell = $row.find(':nth-child(4)');
dataattr = cell[0].getAttribute('data-id');
var selectObject = cell.find("select");
if(selectObject.length){// if it is a select
localobj[dataattr] = selectObject[0].getAttribute('data-key');//val(); previously it was val() here but now I want data-key
}
I tried with this:
$(selectObject/*need to insert something here*/ + ' option:selected').data('key');
but it is showing me an error saying that it is an object Object. I need to insert something after selectObject. Any ideas how to fix that?
Thank you.
Try this $('.form-control').children('option:selected').attr('data-key') using jquery function attr()
console.log($('.form-control').children('option:selected').attr('data-key'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="" data-id="46" contenteditable="true">
<select class="form-control">
<option data-key="end" selected>Opt1</option>
<option data-key="operator_transfer">Opt2</option>
<option data-key="process_script">Opt3</option>
</select>
</td>
For your code you could do like this
var cell = $row.find(':nth-child(4)');
dataattr = cell[0].getAttribute('data-id');
var selectObject = cell.find("select");
if(selectObject.length){// if it is a select
localobj[dataattr] = selectObject[0].getAttribute('data-key');
}
$(selectObject).children('option:selected').data('key');
$('.form-control').change(function(){
alert($('.form-control').find(':selected').attr('data-key'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="" data-id="46" contenteditable="true">
<select class="form-control">
<option data-key="end" selected>Opt1</option>
<option data-key="operator_transfer">Opt2</option>
<option data-key="process_script">Opt3</option>
</select>
</td>
You just need to use the jQuery data() method with the right selector, like this:
$('select option:selected').data('key');
Demo:
var key = $('select option:selected').data('key');
console.log(key);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="" data-id="46" contenteditable="true">
<select class="form-control">
<option data-key="end" selected>Opt1</option>
<option data-key="operator_transfer">Opt2</option>
<option data-key="process_script">Opt3</option>
</select>
</td>
And you can update your code like this:
if (selectObject.length) { // if it is a select
localobj[dataattr] = selectObject[0].getAttribute('data-key');
}
$(selectObject).find('option:selected').data('key');

Code in JQuery 1.7.1 not working in 2.0.2

I am trying to clone last row when Add Row button is clicked as below, this code is working fine with 1.7.1 jquery but if i refer 2.0.2 not working
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
then it is not working.
I have added jquery-migrate-1.1.1.js but still no use.
Please help to resolve.
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<table id="advFilterTable" class="table-filter">
<tbody>
<tr>
<td>
<select id="advFilterColumn1" name="advFilterColumn1" class="chzn-select filter-column" data-placeholder="Select Column" style="width: 120px;">
<option value=SupportDesciption>Support Desciption</option>
<option value=CostCentre.CostCentreCode>Cost Centre</option>
<option value=AdditionalPropertyValue.value>System Roles</option>
<option value=AdditionalProperty.Key>System Role Type</option>
</select>
</td>
<td>
<select id="advFilterOperand1" name="advFilterOperand1" class="chzn-select filter-operand" data-placeholder="Select Operand" style="width: 120px;">
<option value=Equals>Equals</option>
<option value=GreaterThan>GreaterThan</option>
<option value=LessThan>LessThan</option>
<option value=GreaterThanOrEqual>GreaterThanOrEqual</option>
<option value=LessThanOrEqual>LessThanOrEqual</option>
<option value=Contains>Contains</option>
<option value=StartsWith>StartsWith</option>
<option value=EndsWith>EndsWith</option>
</select>
</td>
<td>
<input id="advFilterText1" name="advFilterText1" class="filter-text" style="height: 17px; margin-bottom: 8px" type="text" value=""></input>
</td>
<td>
<button class="btn delete-filter" id="advFilterbtn1" name="advFilterbtn1" style="margin-bottom: 8px"><i class="icon-minus"></i></button>
</td>
</tr>
</tbody>
</table>
<button class="add-filter">Add Row</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(".add-filter").live('click', function(event) {
// clone the last row in the table
var $tr = $('.table-filter').find("tbody tr:last").clone();
// get the name attribute for the input and select fields
$tr.find("input,select").attr("name", function() {
// break the field name and it's number into two parts
var parts = this.id.match(/(\D+)(\d+)$/);
if (parts != null) {
// create a unique name for the new field by incrementing
// the number for the previous field by 1
return parts[1] + ++parts[2];
}
return rollDice();
// repeat for id attributes
}).attr("id", function() {
var parts = this.id.match(/(\D+)(\d+)$/);
if (parts != null) {
return parts[1] + ++parts[2];
}
return rollDice();
});
$('.table-filter').find("tbody tr:last").after($tr);
});
</script>
</body>
</html>
to expand upon Lwyrn's answer,
change
$(".add-filter").live('click', function(event) {
to
$(document.body).on('click', '.add-filter', function(event) {
live function is deprecated in jquery 1.7 and totally removed in 1.9
use .click instead of .live

How to display error message in a Div of the current page using Jquery and Javascript

I am trying to build a page for delivery. My problem as mentioned in the title is that How to display the error message in a div of the current page( say at the top of the form)
Below is my some of my HTML:
<div id="erroMsg"></div>
<form name="shipForm" action="#" method="post" onSubmit="return checkForm()">
<table>
<tr>
<td align="left" bgcolor="#FFFFFF">
<select name="P_COUNTRY">
<option value="AU stralia">Australia</option>
<option value="New zealand">New zealand</option>
<option value="Europe">Europe</option>
<option value="US">US</option>
<option value="Canada">Canada</option>
<option value="other">other</option>
</select>
</td>
<td align="right">
<input type='submit' id="ship" name="submit" value='Next' />
</td>
</tr>
</table>
</form>
Javascript:
function isNull(ele) {
var _form = document.shipForm;
if (_form[ele].value == "") {
_form[ele].focus();
return true;
}
return false;
}
function checkForm() {
var _form = document.shipForm;
if (isNull("P_COUNTRY")) {
$("#erroMsg").html("x Select Country").css("color", "red").css("fontSize", "10px").show();
_form.password.focus();
return false;
}
}
This works for me, however, the content of the message flashes and disappears very quickly.
What I want is actually that to write the message in the div. But since that I redirect my page to current, after refreshing, it's gone, How to avoid this?
Or should I use jQuery? And How?
Guessing you have an error here:
_form.password.focus();
If there's no .password on _form, then .focus() will throw a TypeError, and prevent the return false; from happening.
Remove that line, and it'll likely work.
This works fine for me:
<div id ="erroMsg"></div>
<form name="shipForm" action ="#" method="post" onSubmit="return checkForm()">
<table>
<tr><td align="left" bgcolor="#FFFFFF">
<select name="P_COUNTRY">
<option value="">None</option>
<option value="AU stralia">Australia</option>
<option value="New zealand">New zealand</option>
<option value="Europe">Europe</option>
<option value="US">US</option>
<option value="Canada">Canada</option>
<option value="other">other</option>
</select></td>
<td align ="right"><input type='submit' id ="ship" name= "submit" value='Next'/></td>
</tr></table>
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
function isNull(ele) {
var _form = document.shipForm;
if (_form[ele].value == "") {
_form[ele].focus();
return true;
}
return false;
}
function checkForm(){
var _form = document.shipForm;
if (isNull("P_COUNTRY")) {
$("#erroMsg").html("x Select Country").css("color","red").css("fontSize","10px").show();
return false;
}
}
</script>

Categories

Resources