I have the following JS/jQuery code to append rows to an existing table. Upon appending, I want to show the input field only when "select" or "radio" is selected as the option type.
When I add multiple rows, the input field appearance/disappearance is dependent upon the first added row. I want it to show/hide only on the row(s) where any of the two options are selected.
Hope that made sense. Any suggestion would be helpful. Thanks!
HTML:
<table id="tbl-formfields" class="table vertical-align table-condensed" >
<thead>
<tr>
<th>Input Type</th>
<th>Make Required</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tbody">
<tr id="tr-formField">
<td>
<div>
<select name="formOptionType[]" id="formOptionType">
<option value="">-------------------------------------</option>
<option value="text">Text</option>
<option value="textarea">Textarea</option>
<option value="select">Select Options (Dropdown)</option>
<option value="radio">Radio Buttons</option>
<option value="checkbox">Checkbox</option>
</select>
</div>
<div id="block-optionsInput" style="display:none">
<label>Options:</label><br>
<input id="options" type="text" name="fieldOptions[]" data-role="tagsinput"/>
</div>
</td>
<td>
<label><input type="checkbox" name="fieldRequired[]"/> Required</label>
</td>
<td></td>
</tr>
</tbody>
</table>
jQuery:
//****Repeat form field block****
var repeatBlock = "#tbody";
var repeatText = '<tr class="trRepeat">\n\
<td>\n\
<select class="optType" name="formOptionType[]">\n\
<option value="">-------------------------------------</option>\n\
<option value="text">Text</option>\n\
<option value="textarea">Textarea</option>\n\
<option value="select">Select Options (Dropdown)</option>\n\
<option value="radio">Radio Buttons</option>\n\
<option value="checkbox">Checkbox</option>\n\
</select>\n\
<div class="optBlock" style="display:none">\n\
<label>Options:</label><br>\n\
<input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput"/>\n\
</div>\n\
</td>\n\
<td><label><input type="checkbox" name="fieldRequired[]"/> Required</label></td>\n\
<td><a href="javascript:void(0)" class="removeField" style="color:red" title="Remove this field">\n\
<span class="glyphicon glyphicon-remove"></span></a>\n\
</td></tr>';
$("#btn-addfield").click(function (e) {
e.preventDefault();
$(repeatBlock).append(repeatText);
});
$(repeatBlock).on('click', '.removeField', function (e) {
e.preventDefault();
$(this).parent().parent().remove();
});
//****Show input field when dropdown/radio is selected****
$(repeatBlock).on('change', $(".optType").val(), function (e) {
e.preventDefault();
if ($(this).find(".optType").val() === "radio" || $(this).find(".optType").val() === "select") {
$(this).find(".optBlock").show();
$(".optInput").tagsinput('refresh');
} else {
$(this).find(".optBlock").hide();
}
});
You are passing $(".optType").val() instead of selector, In the event handler test the selected value and use DOM relationship to traverse and target desired element.
$(repeatBlock).on('change', '.optType', function (e) {
e.preventDefault();
var val = $(this).val()
if (val === "radio" || val === "select") {
$(this).closest('tr').find(".optBlock").show();
$(this).closest('tr').find(".optBlock").find(".optInput").tagsinput('refresh');
} else {
$(this).closest('tr').find(".optBlock").hide();
}
});
//****Repeat form field block****
var repeatBlock = "#tbody";
var repeatText = '<tr class="trRepeat">\n\
<td>\n\
<select class="optType" name="formOptionType[]">\n\
<option value="">-------------------------------------</option>\n\
<option value="text">Text</option>\n\
<option value="textarea">Textarea</option>\n\
<option value="select">Select Options (Dropdown)</option>\n\
<option value="radio">Radio Buttons</option>\n\
<option value="checkbox">Checkbox</option>\n\
</select>\n\
<div class="optBlock" style="display:none">\n\
<label>Options:</label><br>\n\
<input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput"/>\n\
</div>\n\
</td>\n\
<td><label><input type="checkbox" name="fieldRequired[]"/> Required</label></td>\n\
<td><a href="javascript:void(0)" class="removeField" style="color:red" title="Remove this field">\n\
<span class="glyphicon glyphicon-remove"></span></a>\n\
</td></tr>';
$("#btn-addfield").click(function(e) {
e.preventDefault();
$(repeatBlock).append(repeatText);
});
$(repeatBlock).on('click', '.removeField', function(e) {
e.preventDefault();
$(this).parent().parent().remove();
});
$(repeatBlock).on('change', '.optType', function(e) {
e.preventDefault();
var val = $(this).val()
if (val === "radio" || val === "select") {
$(this).closest('tr').find(".optBlock").show();
//$(this).closest('tr').find(".optBlock").find(".optInput").tagsinput('refresh');
} else {
$(this).closest('tr').find(".optBlock").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn-addfield">Addfield</button>
<table>
<tbody id="tbody"></tbody>
</table>
Wrap all your input in td inside a otpBlock
<tr class="trRepeat">
<td>
<select class="optType" name="formOptionType[]">
<option value="">-------------------------------------</option>
<option value="text">Text</option>
<option value="textarea">Textarea</option>
<option value="select">Select Options (Dropdown)</option>
<option value="radio">Radio Buttons</option>
<option value="checkbox">Checkbox</option>
</select>
<div class="optBlock" style="display:none">
<label>Options:</label><br>
<input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput" />
</div>
</td>
<td>
<div class="optBlock" style="display:none">
<label><input type="checkbox" name="fieldRequired[]"/> Required</label>
</div>
</td>
<td>
<div>
<a href="javascript:void(0)" class="removeField" style="color:red" title="Remove this field">
<span class="glyphicon glyphicon-remove"></span>Remove</a>
</div>
</td>
</tr>
Use the following JS
//****Show input field when dropdown/radio is selected****
$(repeatBlock).on('change', ".optType", function(e) {
e.preventDefault();
var type = $(this).val(); //Fetch the input type
var container = $(this).closest('tr'); // Get the closest container
container.find('.optBlock').hide(); // Hide all optBlock
container.find('input').filter('[type=' + type + ']').closest('.optBlock').show(); // Show optBlock containing input of type.
});
To Remove
$(repeatBlock).on('click', '.removeField', function(e) {
e.preventDefault();
$(this).closest('tr').remove(); // select the closest tr
});
SNIPPET
var repeatBlock = "#tbody";
var repeatText = '<tr class="trRepeat">\n\
<td>\n\
<select class="optType" name="formOptionType[]">\n\
<option value="">-------------------------------------</option>\n\
<option value="text">Text</option>\n\
<option value="textarea">Textarea</option>\n\
<option value="select">Select Options (Dropdown)</option>\n\
<option value="radio">Radio Buttons</option>\n\
<option value="checkbox">Checkbox</option>\n\
</select>\n\
<div class="optBlock" style="display:none">\n\
<label>Options:</label><br>\n\
<input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput" />\n\
</div>\n\
</td>\n\
<td>\n\
<div class="optBlock" style="display:none">\n\
<label><input type="checkbox" name="fieldRequired[]"/> Required</label></div></td>\n\
<td><div class=""><a href="javascript:void(0)" class="removeField" style="color:red" title="Remove this field">\n\
<span class="glyphicon glyphicon-remove"></span>Remove</a>\n\
</div></td>\
</tr>';
$("#btn-addfield").click(function(e) {
e.preventDefault();
$(repeatBlock).append($(repeatText));
});
$(repeatBlock).on('click', '.removeField', function(e) {
e.preventDefault();
$(this).closest('tr').remove();
});
//****Show input field when dropdown/radio is selected****
$(repeatBlock).on('change', ".optType", function(e) {
e.preventDefault();
var type = $(this).val();
var container = $(this).closest('tr');
container.find('.optBlock').hide();
container.find('input').filter('[type=' + type + ']').closest('.optBlock').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id="tbody"></tbody>
</table>
<button id="btn-addfield">ADD</button>
Related
I have multiple dynamically added select boxes. Options are also dynamically appended. Now what I want is if one of the select boxes with the value 'Lead' is selected now when the user adds another select box then the value with 'Lead' needs to be disabled as there should not be two 'Lead'. Please suggest to me how can I achieve this goal.
<div class="form-group">
<label>Partner Organisation (If there are partners)</label>
<table class="table table-bordered" id="dynamic_field">
<tr>
<td>
<label for="tags">Organisation </label>
<select class="form-control" name="stg_partner_id[]">
<option value="">Select</option>
#foreach($partnerorganisations as $pg)
<option value="{{ $pg->id }}">{{ $pg->partner_organisation }}</option>
#endforeach
</select>
</td>
<td>
<label for="tags">Role </label>
<select class="form-control" name="role[]">
<option value="">Select</option>
#foreach($roles as $role)
<option value="{{ $role }}">{{ $role }}</option>
#endforeach
</select>
</td>
<td>
<button type="button" name="add" id="add" class="btn btn-success">+ </button>
</td>
</tr>
</table>
</div>
Now, my jquery looks like this.
var data = [<?php echo '"'.implode('","', $roles).'"' ?>];
var partnerdata = #json($partnerorganisations);
// console.log(app);
$(document).ready(function(){
var i=0;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><select class="form-control" name="stg_partner_id[]" id="partnerOption'+i+'"><option value="">Select</option></select></td><td><select class="form-control" name="role[]" id="newOption'+i+'"><option value="">Select</option></select></td> <td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></th></tr>');
// console.log(data);
$.each(data, function(key, value) {
$('#newOption'+i+'')
.append($("<option></option>")
.attr("value", value)
.text(value));
});
$.each(partnerdata, function(key, value) {
$("select option:contains('value " + value.id + "')").prop("disabled","disabled");
$('#partnerOption'+i+'')
.append($("<option></option>")
.attr("value", value.id)
.text(value.partner_organisation));
});
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
As there will be mutliple select-boxes you can use .each loop to iterate through all select-boxes and then use that value to add disabled option from other select-box.
Demo Code :
$(document).ready(function() {
var i = 0;
$('#add').click(function() {
i++;
$('#dynamic_field').append('<tr id="row' + i + '"><td><select class="form-control" name="stg_partner_id[]" id="partnerOption' + i + '"><option value="">Select</option><option value="1">A</option><option value="2">B</option><option value="3">C</option></select></td><td><select class="form-control" name="role[]" id="newOption' + i + '"><option value="">Select</option><option value="1">A1</option> <option value="2">B2</option><option value="3">C2</option></select></td> <td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></th></tr>');
//your other codes
check_now(); //call to disable
});
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
$(document).on('change', 'select[name*=stg_partner_id]', function() {
check_now() //on change call as well
})
function check_now() {
//remove disable from all options
$("select[name*=stg_partner_id] option").prop('disabled', false)
//loop through select box
$("select[name*=stg_partner_id]").each(function() {
var values = $(this).val()
if (values != "") {
//find option where value matches disable them
$("select[name*=stg_partner_id]").not(this).find("option[value=" + values + "]").prop('disabled', true);
}
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="form-group">
<label>Partner Organisation (If there are partners)</label>
<table class="table table-bordered" id="dynamic_field">
<tr>
<td>
<label for="tags">Organisation </label>
<select class="form-control" name="stg_partner_id[]">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
</td>
<td>
<label for="tags">Role </label>
<select class="form-control" name="role[]">
<option value="">Select</option>
<option value="1">A1</option>
<option value="2">B2</option>
<option value="3">C2</option>
</select>
</td>
<td><button type="button" name="add" id="add" class="btn btn-success">+
</button></td>
</tr>
</table>
</div>
I have to display list of values in table format. I pass id in input textbox value future I will hide it, and my question is how to get textbox value when I changed the dropdown value.When I changed dropdown it's will update on particular id. Here I have attached my screenshot. Thanks in Advance. i have tried this below code but its will take first id only.
<td>
<select name="type" id="type" class="form-control">
<option value="general">General</option>
<option value="coin">Coin</option>
<option value="token">Token</option>
</select>
</td>
<td>
<input type="hidden" id="comp_id" value="<?php echo $row['company_id']; ?>">
</td>
<script>
$(document).ready(function() {
var type_val;
$('#type').on('change', function() {
var fav = $('#comp_id').val();
alert(fav);
type_val = $('#type').val();
console.log(type_val);
});
});
</script>
expected output
<td>
<select name="type" id="type" class="form-control">
<option value="general">General</option>
<option value="coin">Coin</option>
<option value="token">Token</option>
</select>
</td>
<td>
<input type="hidden" id="comp_id" value="<?php echo $row['company_id']; ?>">
</td>
<script>
$(document).ready(function() {
var type_val;
$('#type').on('change', function() {
// find parent tr then find #comp_id inside it
var fav = $(this).closest('tr').find('#comp_id').val();
alert(fav);
type_val = $('#type').val();
console.log(type_val);
});
</script>
You can use parent and next like this.
$(document).ready(function() {
$('#type').on('change', function() {
$(this).parent().next('td').find('input').val()
});
});
Note: Don't use repeated ID. Its a rule violation. Use class instead
of id to find input.Its take only 1st id because duplicate id is not allowed.
Working snippet.
$('#type').on('change', function() {
console.log($(this).parent().next('td').find('input').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select name="type" id="type" class="form-control">
<option value="general">General</option>
<option value="coin">Coin</option>
<option value="token">Token</option>
</select>
</td>
<td>
<input type="hidden" class="comp_class" value="Your Value From Php">
</td>
</tr>
</table>
Never use multiple id's of same name on single page.
Generate your id's dynamically like type1, type2 ... and comp1, comp2 ...
<table>
<tr>
<td>
<select name="type1" id="type1" class="form-control sel">
<option value="general">General</option>
<option value="coin">Coin</option>
<option value="token">Token</option>
</select>
</td>
<td>
<input type="hidden" id="comp_id1" value="1">
</td>
</tr>
<tr>
<td>
<select name="type2" id="type2" class="form-control sel">
<option value="general">General</option>
<option value="coin">Coin</option>
<option value="token">Token</option>
</select>
</td>
<td>
<input type="hidden" id="comp_id2" value="2">
</td>
</tr>
</table>
<script>
$('.sel').change(function(){
var select_id = $(this).attr('id');
var offset = select_id.substring(4);
var type = $(this).val();
alert(type);
var comp = $('#comp_id'+offset).val();
alert(comp);
});
</script>
Here is jsfiddle link:
jsFiddle
I have a form and user can dynamically add some text-feild to this form by clicking on dropdown and choosing what he wants to add.
How to post only these text feilds to php script using jquery
code:
<form id="sms_frm" name="sms_frm">
<tr>
<td width="17%"><label>Http URL</label></td>
<td >
<div class='input-group'>
<div class='input-group-addon'>
<i class='fa fa-television'></i>
</div>
<input type='text' class='form-control' id='smsurl' name='smsurl' >
</div>
</td>
<td></td>
</tr>
<tr id="element"></tr>
<tr>
<td>
<div class='input-group'>
<select name="sms_sel" class="form-control" style="margin: 10px" id="sms_sel">
<option value="username">UserName</option>
<option value="Password">Password</option>
<option value="APIKEY">APIKEY</option>
<option value="company">company</option>
<option value="Originator">Originator</option>
<option value="ServiceCode">ServiceCode</option>
<option value="sender">sender</option>
<option value="ServiceUrl">ServiceUrl</option>
<option value="ServicePassword">ServicePassword</option>
<option value="header">header</option>
<option value="OriginName">OriginName</option>
<option value="not">Not any of this</option>
</select>
</div>
</td>
<td><input type='text' class='form-control' id='vals' style="margin: 10px; float: right" name='vals' >
</td>
<td></td>
</tr>
</tbody></table>
this is ajax code to send text fields to php script but it not working
$(document).ready(function(){
$("#sms_frm").submit(function(event){
event.preventDefault(); //prevent default action
var arrays=new array();
var number = $(' input[type=text]');
$('#sms_frm input[type=text]').each(function () {
arrays.push(this);
});
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url : "Save.php?id=sms_api",
type: 'post',
data : arrays
}).done(function(response){ //
$("#res").html(response);
});
});
});
</script>
if user choose sender for example new text field with id ='sender' and name ='sender' will be append
I don't want to send the select item with ajax
I only want text fields
Please try this code this may work...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sms_frm" name="sms_frm">
<table id="text-table">
<tr>
<td width="17%"><label>Http URL</label></td>
<td>
<div class='input-group'>
<div class='input-group-addon'><i class='fa fa-television'></i></div>
<input type='text' class='form-control' id='smsurl' name='smsurl' >
</div>
</td>
<td></td>
</tr>
<tr id="element"></tr>
<tr>
<td>
<div class='input-group'>
<select name="sms_sel" class="form-control" style="margin: 10px" id="sms_sel">
<option value="username">UserName</option>
<option value="Password">Password</option>
<option value="APIKEY">APIKEY</option>
<option value="company">company</option>
<option value="Originator">Originator</option>
<option value="ServiceCode">ServiceCode</option>
<option value="sender">sender</option>
<option value="ServiceUrl">ServiceUrl</option>
<option value="ServicePassword">ServicePassword</option>
<option value="header">header</option>
<option value="OriginName">OriginName</option>
<option value="not">Not any of this</option>
</select>
</div>
</td>
<td>
<input type='text' class='form-control' id='vals' style="margin: 10px; float: right" name='vals' >
</td>
<td>
</td>
</tr>
</table>
</form>
<script>
$('#sms_sel').change(function(e) {
var name=$(this).val();
var value=$('#vals').val();
$('<tr><td width="17%"><label>'+name+'</label></td><td><input type="text" sms="sms" class="form-control ss" id="'+name+'" name="'+name+'" value="'+value+'" ></td><td></td><tr>').insertBefore($(this).closest('tr'));
});
</script>
In your jQuery, select only text fields. You can do that in multiple ways -
By directly accessing the tag $('input[text]');
By assigning a class to every text field and then accessing based on that class like `$('.some-class');
By assigning a data-* rule and then accessing it like $('input').data(YOUR_RULE);
After selecting your text fields, submit your form.
Suppose I have this form with indexed input fields username and level:
<form>
<table>
<tr class="trToClone">
<td>
<label>Username:</label>
<input type="text" name="username[0]" />
</td>
<td>
<label>Level:</label>
<select name="level[0]">
<option value="">---</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</td>
<td><input type="button" class="addField" value="Add" /></td>
</tr>
</table>
</form>
The row can be repeated using this jQuery:
$("input.addField").on('click', function() {
var $tr = $(this).closest('.trToClone');
var $clone = $tr.clone();
$clone.find(':text').val('');
$tr.after($clone);
});
Now for every subsequent row I add, I want to increase the indices of the name attribute (i.e. username[1],level[1]; username[2],level[2]; and so on...). How can I do this? I've looked for possible solutions, but to no avail.
Specify new index with $('.trToClone').length, modify it on each element with name attribute with jQuery .attr() method:
$("input.addField").on('click', function() {
var $tr = $(this).closest('.trToClone');
var $clone = $tr.clone(true, true);
var $names = $clone.find('[name]');
var trIndex = $('.trToClone').length;
$names.each(function(index, element) {
var newName = $(element).attr('name').replace(/[0-9]/g, trIndex);
$(element).attr('name', newName);
console.log($(element).attr('name'));
});
$clone.find(':text').val('');
$tr.after($clone);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<table>
<tr class="trToClone">
<td>
<label>Username:</label>
<input type="text" name="username[0]" />
</td>
<td>
<label>Level:</label>
<select name="level[0]">
<option value="">---</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</td>
<td><input type="button" class="addField" value="Add" /></td>
</tr>
</table>
</form>
UPDATE: changing name attributes dynamically.
you can use a counter for counting your clicks! You have to move the "add" click button out of the table row.
HTML:
<form>
<input type="button" class="addField" value="Add" />
<table>
<tr class="trToClone">
<td>
<label>Username:</label>
<input type="text" name="username[0]" />
</td>
<td>
<label>Level:</label>
<select name="level[0]">
<option value="">---</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</td>
<td></td>
</tr>
</table>
</form>
JS:
var counter = 0;
$("input.addField").on('click', function() {
counter++;
var $tr = $('.trToClone:eq(0)');
var $clone = $tr.clone();
var newTextName = $clone.find(':text').attr('name').replace(/\[(\d)+\]/,'[+ counter +']');
$clone.find(':text').attr('name',newTextName);
$clone.find('.dropdown').attr('name','level['+ counter + ']');
$tr.parent().append($clone);
});
check out this fiddle: https://jsfiddle.net/gknrfw1g/2/
$('.addField').click(function(){
var count = $('#btnIncrease').val();
var $tr = $(this).closest('.trToClone');
var $clone = $tr.clone();
count++;
$('#btnIncrease').val(count);
$clone.find(':text').val('');
$clone.find(':text').attr('name', 'username[' + count + ']');
$tr.after($clone);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="trToClone">
<td>
<label>Username:</label>
<input type="text" name="username[0]" />
</td>
<td>
<label>Level:</label>
<select name="level[0]">
<option value="">---</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</td>
<td><input type="button" class="addField" value="Add" /></td>
</tr>
</table>
<input type="hidden" id="btnIncrease" value="0" />
This would work for you.
For adding the name attribute you first need to find the index of current row and then you can add 1 to the index and again update the name attribute for both text and select list. Try with the code below-
Note- You should also hide the add button from previous row and bind the click function again for the newly cloned row.
$("input.addField").on('click', function() {
var $tr = $(this).closest('.trToClone');
var $clone = $tr.clone();
var lastIndexName= $clone.find(':text').attr("name").split('[');
var lastIndex=parseInt(lastIndexName[1].substring(0,1));
var updatedNameValue="username["+(lastIndex+1)+"]";
$clone.find(':text').attr("name",updatedNameValue);
$clone.find(':text').val('');
$clone.find('select').attr("name","level["+(lastIndex+1)+"]")
$tr.after($clone);
});
Suppose there is a link (two links, actually), each supposed to be doing something similar and each doing something different.
<a style="cursor:pointer;" name="A">#</a>
<a style="cursor:pointer;" name="A">Product A</a>
<a style="cursor:pointer;" name="B">#</a>
<a style="cursor:pointer;" name="B">Product B</a>
etc.
When the # anchor is clicked, it needs to open a popup, prompt for a number, then on submit, autoselect the option and set textarea value to the number entered.
<select>
<option selected="selected" value="0"></option>
<option value="A">Spies</option>
<option value="B">Militia</option>
</select>
</td>
<td><input value="0" type="text"></td>
But when the Product anchor is clicked, it needs to do the same thing, but just set the selected element to the corresponding value (Product A autoselects the selects to A, etc.)
I have some stuff in JavaScript to make this work, but I'd like it to be in jQuery, and am having a hard time figuring it out.
Some JS:
The anchors have onclick="var newNumUnits=prompt('How many of Product X do you want to default to? 'Enter amount here'); quickFill(1111115,newNumUnits);", which takes care of a lot of the stuff, but it gets "large" and "complicated", and I'd really like to see the code be rendered easier (if possible) in jQuery.
function quickFill(ProdID, num) {
for(i=0; i<document.myForm.elements.length; i++) {
fieldname = document.myForm.elements[i].name;
fieldvalue = document.myForm.elements[i].value;
if (fieldname.indexOf("_") != -1) {
fieldNameArray = fieldname.split("_");
smallFieldName = fieldNameArray[0];
myPUID = fieldNameArray[1];
if (smallFieldName == "ProdID") {
selectfield = document.myForm.elements[i];
for (var j=0; j<selectfield.options.length;j++) {
if (selectfield.options[j].value == ProdID) {
selectfield.options[j].selected=true;
textinputfield = document.getElementById("num_"+myPUID);
textinputfield.value=num;
}
}
}
}
}
updateStatus();
}
Any help would be appreciated.
EDIT: The actual, unedited code that I'm currently working with:
<tr class="L1">
<td></td>
<td>1898, 2018
</td>
<td>9</td>
<td>Combat Outpost
</td>
<td>
<select name="struct[213][str]">
<option selected="selected" value="0"></option>
<option value="U2" data-price="4000">Blackshirts</option>
<option value="U3" data-price="6000">Spies</option>
<option value="U4" data-price="8000">Partisans</option>
<option value="U7" data-price="15000">Rebels</option>
<option value="U11" data-price="80000">Oerlikon Cannons</option>
</select>
</td>
<td>
<input size="2" maxlength="4" class="txt" name="struct[213][numUnits]" value="0" type="text">
</td>
</tr>
<tr class="L2">
<td></td>
<td>1900, 2018
</td>
<td>9</td>
<td>Combat Outpost
</td>
<td>
<select name="struct[329][str]">
<option selected="selected" value="0"></option>
<option value="U2" data-price="4000">Blackshirts</option>
<option value="U3" data-price="6000">Spies</option>
<option value="U4" data-price="8000">Partisans</option>
<option value="U7" data-price="15000">Rebels</option>
<option value="U11" data-price="80000">Oerlikon Cannons</option>
</select>
</td>
<td>
<input size="2" maxlength="4" class="txt" name="struct[329][numUnits]" value="0" type="text">
</td>
</tr>
<tr class="L2">
<td></td>
<td>1901, 2018
</td>
<td>9</td>
<td>Military Installation
</td>
<td>
<select name="struct[330][str]">
<option selected="selected" value="0"></option>
<option value="U1" data-price="1200">K-9 Corps</option>
<option value="U5" data-price="9000">Riflemen</option>
<option value="U6" data-price="11000">Sappers</option>
<option value="U8" data-price="24000">Jägers</option>
<option value="U9" data-price="27000">Commandos</option>
<option value="U10" data-price="33000">Red Berets</option>
<option value="U12" data-price="110000">Ford GPW</option>
<option value="U13" data-price="222000">M3 Half-tracks</option>
<option value="U14" data-price="350000">7TP</option>
</select>
</td>
<td>
<input size="2" maxlength="4" class="txt" name="struct[330][numUnits]" value="0" type="text">
</td>
</tr>
<tr class="L2">
<td></td>
<td>1901, 2017
</td>
<td>9</td>
<td>Light Airfield
</td>
<td>
<select name="struct[331][str]">
<option selected="selected" value="0"></option>
<option value="U15" data-price="155000">PZL.23 Karaś</option>
<option value="U16" data-price="175000">R-4 Hoverfly</option>
<option value="U17" data-price="650000">PZL P.11</option>
<option value="U18" data-price="1050000">P-39 Airacobra</option>
<option value="U19" data-price="1500000">C-46 Commando</option>
</select>
</td>
<td>
<input size="2" maxlength="4" class="txt" name="struct[331][numUnits]" value="0" type="text">
</td>
</tr>
Some stuff that I experimented with before, in JavaScript, that works (goes with the the quickFill function posted above:
<a style="cursor:pointer;" onclick="var newNumUnits=prompt('How many units do you want to default to? \nClick the unit name instead of the number sign to skip this step.','Enter amount here'); quickFill(U3,newNumUnits);">#</a>
<a style="cursor:pointer;" onclick="quickFill(U3);">Spies</a>
<br>
<a style="cursor:pointer;" onclick="var newNumUnits=prompt('How many units do you want to default to? \nClick the unit name instead of the number sign to skip this step.','Enter amount here'); quickFill(U2,newNumUnits);">#</a>
<a style="cursor:pointer;" onclick="quickFill(U2);">Blackshirts</a>
That style of anchors then continues for about 30 more combos, different U#'s, different names. What needs to happen is that when the anchor with text is clicked, all selects that contain that same U# are then auto-selected to it, and when the # anchor is clicked, the same thing happens, but also changes the corresponding textarea to the number entered in the prompt.
You will need to do some changes to the HTML <a> tags first:
<a style="cursor:pointer;" name="A" data-type="hash">#</a>
<a style="cursor:pointer;" name="A" data-type="product">Product A</a>
<a style="cursor:pointer;" name="B" data-type="hash">#</a>
<a style="cursor:pointer;" name="B" data-type="product">Product B</a>
<select>
<option selected="selected" value="0"></option>
<option value="A">Spies</option>
<option value="B">Militia</option>
</select>
<input value="0" type="text">
Now in jQuery you will need to listen for the click event of the <a> tag:
$(document).ready(function(){
$('a').on('click', function (e) {
e.preventDefault();
var a_name = $(this).attr('name');
if ($(this).data('type') === 'hash') {
var answer = prompt('Type your selection', '');
$('select option').prop('selected', false);
$('select option[value="' + a_name + '"]').prop('selected', true);
$('input').val(answer);
} else if ($(this).data('type') === 'product') {
$('select option').prop('selected', false);
$('select option[value="' + a_name + '"]').prop('selected', true);
}
});
});
JSFIDDLE DEMO
Update since you showed me full code =)
HTML
<table id="someID">
<tr class="L1">
<td></td>
<td>1898, 2018
</td>
<td>9</td>
<td>Combat Outpost
</td>
<td>
<select name="struct[213][str]">
<option selected="selected" value="0"></option>
<option value="U2" data-price="4000">Blackshirts</option>
<option value="U3" data-price="6000">Spies</option>
<option value="U4" data-price="8000">Partisans</option>
<option value="U7" data-price="15000">Rebels</option>
<option value="U11" data-price="80000">Oerlikon Cannons</option>
</select>
</td>
<td>
<input size="2" maxlength="4" class="txt" name="struct[213][numUnits]" value="0" type="text">
</td>
</tr>
<tr class="L2">
<td></td>
<td>1900, 2018
</td>
<td>9</td>
<td>Combat Outpost
</td>
<td>
<select name="struct[329][str]">
<option selected="selected" value="0"></option>
<option value="U2" data-price="4000">Blackshirts</option>
<option value="U3" data-price="6000">Spies</option>
<option value="U4" data-price="8000">Partisans</option>
<option value="U7" data-price="15000">Rebels</option>
<option value="U11" data-price="80000">Oerlikon Cannons</option>
</select>
</td>
<td>
<input size="2" maxlength="4" class="txt" name="struct[329][numUnits]" value="0" type="text">
</td>
</tr>
<tr class="L2">
<td></td>
<td>1901, 2018
</td>
<td>9</td>
<td>Military Installation
</td>
<td>
<select name="struct[330][str]">
<option selected="selected" value="0"></option>
<option value="U1" data-price="1200">K-9 Corps</option>
<option value="U5" data-price="9000">Riflemen</option>
<option value="U6" data-price="11000">Sappers</option>
<option value="U8" data-price="24000">Jägers</option>
<option value="U9" data-price="27000">Commandos</option>
<option value="U10" data-price="33000">Red Berets</option>
<option value="U12" data-price="110000">Ford GPW</option>
<option value="U13" data-price="222000">M3 Half-tracks</option>
<option value="U14" data-price="350000">7TP</option>
</select>
</td>
<td>
<input size="2" maxlength="4" class="txt" name="struct[330][numUnits]" value="0" type="text">
</td>
</tr>
<tr class="L2">
<td></td>
<td>1901, 2017
</td>
<td>9</td>
<td>Light Airfield
</td>
<td>
<select name="struct[331][str]">
<option selected="selected" value="0"></option>
<option value="U15" data-price="155000">PZL.23 Karaś</option>
<option value="U16" data-price="175000">R-4 Hoverfly</option>
<option value="U17" data-price="650000">PZL P.11</option>
<option value="U18" data-price="1050000">P-39 Airacobra</option>
<option value="U19" data-price="1500000">C-46 Commando</option>
</select>
</td>
<td>
<input size="2" maxlength="4" class="txt" name="struct[331][numUnits]" value="0" type="text">
</td>
</tr>
</table>
<hr />
<div id="quickChoice"> <a style="cursor:pointer;">#</a>
<a style="cursor:pointer;">Spies</a>
<br>
<a style="cursor:pointer;">#</a>
<a style="cursor:pointer;">Blackshirts</a>
<br>
<a style="cursor:pointer;">#</a>
<a style="cursor:pointer;">Riflemen</a>
<br>
<a style="cursor:pointer;">#</a>
<a style="cursor:pointer;">Sappers</a>
<br>
<a style="cursor:pointer;">#</a>
<a style="cursor:pointer;">R-4 Hoverfly</a>
</div>
jQuery
$(document).ready(function(){
$('div#quickChoice').on('click', 'a', function (e) {
// dont allow the <a> to perform its default functionality
e.preventDefault();
// get content of <a> tag
var contents = $(this).text();
// user clicked hash symbol
if (contents === '#') {
// get the contents of next available <a> tag
var select_choice = $(this).next('a').text();
// promp for number
var answer = prompt('Type your selection', '');
// go through table
// find any <selects> that have <options>
// filter options based on <a> contents next to hash
// make it selected
// for each matching <option> go to parent <td> and find the next <td> because we need to populate the <input> tag
// populate the <input>
$('table#someID')
.find('select')
.find('option')
.filter(function () {
if ($(this).text() === select_choice) {
return true;
} else {
return false;
}
}).prop('selected', true)
.each(function () {
$(this)
.parents('td')
.first()
.next('td')
.find('input[type="text"]')
.val(answer);
});
} else {
// user did not click hash but rather the text value
var select_choice = $(this).text();
// same as above but we don't have to populate the <input> at all
$('table')
.find('select')
.find('option')
.filter(function () {
if ($(this).text() === select_choice) {
return true;
} else {
return false;
}
}).prop('selected', true);
}
});
});
JSFIDDLE DEMO