I have a button that allows the user to add another row to add different types of returned equipment. I am posting this data to another page to print out. If I try and retrieve the data from the post array, I can only get the last in the entry
I've tried setting the name to name="device[]" then adding a value of "key" but since I'm using a drop down select, I can't do that.
<select name="device-type[]">
<option value="" disabled selected hidden>Select Equipment Type</option>
<option value="dvr">DVR</option>
<option value="modem">Modem</option>
<option value="router">Router</option>
<option value="other">Other</option>
</select>
I have a button that calls a JS function to just add another select element identical to that.
JS code:
function addBox(){
$("#devices").append('<select name="device-type" class="focus:outline-none plain-field">\n' +
' <option>Select Equipment Type</option>\n' +
' <option value="dvr">DVR</option>\n' +
' <option value="modem">Modem</option>\n' +
' <option value="router">Router</option>\n' +
' <option value="other">Other</option>\n' +
' </select>\n' +
' <input class="focus:outline-none plain-field" name="device-number" type="text" placeholder="CMAC/SN">\n' +
' <input type="checkbox" name="power-cord" class="">Power Cord?\n' +
' <input type="checkbox" name="remote" class="">Remote?\n' +
' <br>');
return false;
PHP to retrieve the information from that:
<p><?php echo $_POST['device-type']?></p>
<p><?php echo $_POST['device-number']?></p>
My question is, how can I retrieve the device type and number in the post array?
Simply make your HTML select tag accept multiple values. E.g:
<select name="device_type[]" class="focus:outline-none plain-field" multiple>
....
</select>
You can get the selected values on the PHP end using $_POST['device_type']
Refer to store multiple select option into a PHP array for more information
It looks like you need to add [] brackets to your field names to make them a multi array for $_POST to handle processing. Also, if you want to identify each row by an index, on clicking the ADD button, you can count the amount of select boxes generated to create a count and use that as the key index for each array. If you run the following below in a PHP file, click the ADD button to add some select boxes, and then click SUBMIT, you will see your data echo'd out as a multi-dimensional array. I also gave your initial select box an index of 0 for the multi array.
<?php
if(isset($_POST) && !empty($_POST)) {
echo "<pre>";
print_r($_POST);
foreach($_POST['device-type'] as $key => $type) {
echo "<b>Type:</b> " . $type . " ";
echo (isset($_POST['device-number']) && isset($_POST['device-number'][$key]) && !empty($_POST['device-number'][$key])) ? "<b>Number:</b> " .$_POST['device-number'][$key] . " " : "";
echo (isset($_POST['power-cord']) && isset($_POST['power-cord'][$key]) && !empty($_POST['power-cord'][$key])) ? "<b>Power Cord:</b> " .$_POST['power-cord'][$key] . " " : "";
echo (isset($_POST['remote']) && isset($_POST['remote'][$key]) && !empty($_POST['remote'][$key])) ? "<b>Remote:</b> " .$_POST['remote'][$key] . " " : "";
echo "<br/>";
}
echo "</pre>";
}
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function addBox() {
//console.log($('select.plain-field').length + 1);
var rowCount = $('select.plain-field').length + 1;
$("#devices").append('<br/><select name="device-type[' + rowCount + ']" class="focus:outline-none plain-field">\n' +
' <option value="">Select Equipment Type</option>\n' +
' <option value="dvr">DVR</option>\n' +
' <option value="modem">Modem</option>\n' +
' <option value="router">Router</option>\n' +
' <option value="other">Other</option>\n' +
' </select>\n' +
' <input class="focus:outline-none plain-field" name="device-number[' + rowCount + ']" type="text" placeholder="CMAC/SN">\n' +
' <input type="checkbox" name="power-cord[' + rowCount + ']" class="">Power Cord?\n' +
' <input type="checkbox" name="remote[' + rowCount + ']" class="">Remote?\n' +
' ');
return false;
}
</script>
<form action="" method="post">
<div id="devices">
<select name="device-type[0]">
<option value="">Select Equipment Type</option>
<option value="dvr">DVR</option>
<option value="modem">Modem</option>
<option value="router">Router</option>
<option value="other">Other</option>
</select>
</div>
<input type="button" onclick="addBox();" value="Add [+]" />
<br/>
<br/>
<input type="submit" value="Submit" />
</form>
Related
I'm having trouble making dynamically added inputs required. especially with the "select" input
I have already tried manually checking (wo Jquery validate) if inputs submitted were correct but i encountered the same kind of problem. The "required" class doesn't help either.
Here's the html :
<form id='myform'>
<div>
<div id="addRow">+</div>
<div id="deleteRow">-</div>
</div>
<div>
<table id="tableex">
<tr>
<td>
<select name="selectbox[]" data-selected="" class='selectdyna required'>
<option value="" selected="selected" disabled="disabled">env :</option>
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
</select>
</td>
</tr>
</table>
</div>
<div>
<input type='submit' value='Validate'>
</div>
</form>
here's my js:
$(document).ready(function() {
$("#addRow").click(function() {
var str = "<tr>\n" +
" <td id=\"selecttd\">\n" +
" <select name=\"selectbox[]\" class='selectdyna required' data-selected=\"\">\n" +
" <option value=\"\" selected=\"selected\" >env :</option>\n" +
" <option value=\"1\">option1</option>\n" +
" <option value=\"2\">option2</option>\n" +
" <option value=\"3\">option3</option>\n" +
" </select>\n" +
" </td>\n" +
" </tr>";
$("#tableex").append(str)
$('#myform').validate();
$('.selectdyna').rules('add', { 'required': true });
})
$("#deleteRow").click(function() {
if ($("#tableex tr").length > 1) {
$("#tableex tr:last").remove();
} else {
alert("there must been one line minimum.")
}
})
})
here's a link to the fiddle: https://jsfiddle.net/v3tj2c5u/
I don't understand why you require the name of the dropdown that way.
You can do it as below demo
$(document).ready(function() {
$("#addRow").click(function() {
var count= $("#tableex tr").length+1;
var str = "<tr>\n" +
" <td id=\"selecttd\">\n" +
" <select name=\"selectbox"+count+"\" class='selectdyna required' data-selected=\"\">\n" +
" <option value=\"\" selected=\"selected\" >env :</option>\n" +
" <option value=\"1\">option1</option>\n" +
" <option value=\"2\">option2</option>\n" +
" <option value=\"3\">option3</option>\n" +
" </select>\n" +
" </td>\n" +
" </tr>";
$("#tableex").append(str)
$('#myform').validate();
$('.selectdyna').rules('add', { 'required': true });
})
$("#deleteRow").click(function() {
if ($("#tableex tr").length > 1) {
$("#tableex tr:last").remove();
} else {
alert("there must been one line minimum.")
}
})
})
Working demo
I am working on a country dropdown filter for a search. This will allow users to search within the selected region.
Select 'Thailand' from the dropdown, 'Thailand + ' will be pushed to the search box which allows user to enter another keyword (e.g. Food) which forms into
'Thailand + Food'.
Due to technical constraints this is my only workaround creating a search filter. I am wondering can i make the selected region text invisible (Thailand +) yet when i press enter.. 'Thailand +' is part of the search results.
What i want to achieve:
User selects 'Thailand'
Thailand +' is pushed to textbox (Not visible to user)**
User types 'Food' in the search box
Both 'Thailand + Food' is in the search result
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testfloat">
<select id="quantity">
<option selected>Select Libraries</option>
<option value="Albanian + ">Albanian</option>
<option value="Singapore + ">Singapore</option>
<option value="Malaysia + ">Malaysia</option>
<option value="Germany + ">Germany</option>
<option value="France + ">France</option>
<option value="Thailand + ">Thailand</option>
</select>
<script type="text/javascript">
$('#quantity').change(function(){
var qty = $('#quantity').val();
var total = qty;
$("#ms-helperText").val(total);
});
</script>
<input type="text" id="ms-helperText">
Instead of putting the selected country in the input, store it in a variable and change it accordingly.
This is how should be your code:
var searchedCountry = "";
$('#quantity').change(function() {
searchedCountry = $('#quantity').val();
$("#preview").html(searchedCountry + " " + $('#ms-helperText').val());
});
$('#ms-helperText').keyup(function() {
$("#preview").html(searchedCountry + " " + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testfloat">
<select id="quantity">
<option selected>Select Libraries</option>
<option value="Albanian + ">Albanian</option>
<option value="Singapore + ">Singapore</option>
<option value="Malaysia + ">Malaysia</option>
<option value="Germany + ">Germany</option>
<option value="France + ">France</option>
<option value="Thailand + ">Thailand</option>
</select>
<input type="text" id="ms-helperText">
<br/>
<div id="preview">
</div>
you could try to attach that value into a hidden input in html
<input type="hidden" id="somehiddenvalue"></input>
Concat both values into a hidden form element:
// Get all needed input elements
const $country = document.querySelector( '#country' );
const $quantity = document.querySelector( '#quantity' );
const $msHelperText = document.querySelector( '#ms-helperText' );
// Event handler
function inputChange() {
const collection = [];
$country.value && collection.push( $country.value );
$quantity.value && collection.push( $quantity.value );
// Only add + if both inputs have a value.
$msHelperText.value = collection.join( ' + ' );
console.log( 'Hidden element value: ', $msHelperText.value );
}
$country.addEventListener( 'input', inputChange );
$quantity.addEventListener( 'input', inputChange );
<select id="country">
<option value="" selected>Select Libraries</option>
<option value="Albanian">Albanian</option>
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Germany">Germany</option>
<option value="France">France</option>
<option value="Thailand">Thailand</option>
</select>
<input type="text" id="quantity">
<!-- the new hidden form element, that will hold both values -->
<input type="hidden" id="ms-helperText">
I am looking to change the input type of a number selector to a dropdown if the value is less than 10. For values greater than 9 (10+) the input type should change back to a number selector.
Amazon and Sears.com are doing this style of quantity selectors in their shopping carts for some desktop users (subject to AB testing).
My issue is that it will change input type once, but not back again.
Additionally what is the best practice to retain the value between input types? I've considered either using a variable or copying to a hidden input which is the actual field submitted.
HTML:
<label class="mylabel">Quantity:</label>
<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number">
<input type="submit" name="btnAddToCart" value="Add To Cart" id="btnAddToCart" class="">
jQuery:
$(".qty-input").change(function(){
if (parseInt(this.value) < 10){
$(".qty-input").replaceWith(
'<select id="txtQuantity" name="txtQuantity" class="qty-input">' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'<option value="4">4</option>' +
'<option value="5">5</option>' +
'<option value="6">6</option>' +
'<option value="7">7</option>' +
'<option value="8">8</option>' +
'<option value="9">9</option>' +
'<option value="10">10+</option>' +
'</select>'
);
}
if (parseInt(this.value) > 9){
$(".qty-input").replaceWith(
'<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number">'
);
}
});
There is no need to render and re-render the fields each time they should switch. It is easier to simply hide them.
A very basic solution, error handling and styling is up to you:
var high = $('#high')
var low = $('#low')
function onChange() {
if (low.is(':visible')) {
var value = low.val();
high.val(value);
if (parseInt(value) > 9) toggleInputs();
} else {
var value = high.val();
low.val(value);
if (parseInt(value) <= 9) toggleInputs();
}
}
function toggleInputs() {
$('#low').toggle();
$('#high').toggle();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Quantity:</label>
<input onchange='onChange()' id='high' style='display: none' />
<select onchange='onChange()' id='low'>
<option value='0'>0</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10+</option>
</select>
You can do it with two particular different selectors one for dropdown other for text to take getter than ten.selecting 10+ will change the select control name and it will be point to your textbox name or if want to switch back then restore the old name of select box and remove text box name.
Using jquery toggle method and prop attribute you can handle or modify name prop of the controls you are using.I think you got it.
Your server side code can catch the post data easily with this logic.
If not getting, can ask for sample code i can show you.
Although there are better ways of doing this I'm posting this to answer why your version is not working. Basically you're binding to an element that doesn't exist yet i.e. dynamic content.
Jquery handles this using the on method.
You can get it to work by adding a static ancestor and binding to that instead. For a better understanding of how event bubbling and delegation works check out this link. http://api.jquery.com/on/
Something like this
HTML
<label class="mylabel">Quantity:</label>
<div id="staticAncestor">
<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number">
</div>
JS
$("#staticAncestor").on("change",'.qty-input',function(){
if (parseInt(this.value) < 10 && !$( "#txtQuantity" ).length){
$(".qty-input").replaceWith(
'<select id="txtQuantity" name="txtQuantity" class="qty-input">' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'<option value="4">4</option>' +
'<option value="5">5</option>' +
'<option value="6">6</option>' +
'<option value="7">7</option>' +
'<option value="8">8</option>' +
'<option value="9">9</option>' +
'<option value="10">10+</option>' +
'</select>'
);
}
if (parseInt(this.value) > 9){
$(".qty-input").replaceWith(
'<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number">'
);
}
});
Here is the pen http://codepen.io/anon/pen/jAQogj
Cheers and happy coding!
The problem is this...
once you remove the object from the DOM you are also removing the event handler if you still want to take the replace approach you would have to re-bind the event handler something like
$(document).ready(function() {
function test(){
if (parseInt(this.value) < 10) {
$(".container ").html(
'<select id="txtQuantity" name="txtQuantity" class="qty-input">' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'<option value="4">4</option>' +
'<option value="5">5</option>' +
'<option value="6">6</option>' +
'<option value="7">7</option>' +
'<option value="8">8</option>' +
'<option value="9">9</option>' +
'<option value="10">10+</option>' +
'</select>'
);
} else {
$(".container").html(
'<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number">'
);
}
$(".qty-input").on('change', test);
}
$(".qty-input").on('change', test);
});
https://jsfiddle.net/happymacarts/pn1qeyg9/1/
This will work. Your example doesn't work since when you replace the DOM node/element, it no longer has the change event handled so function is bonded nor executed.
$(".qty-input").change(updateControl);
function updateControl(evt) {
var template;
if (parseInt(this.value) < 10 && this.tagName.toLowerCase() === "input") {
template =
'<select id="txtQuantity" name="txtQuantity" class="qty-input">' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'<option value="4">4</option>' +
'<option value="5">5</option>' +
'<option value="6">6</option>' +
'<option value="7">7</option>' +
'<option value="8">8</option>' +
'<option value="9">9</option>' +
'<option value="10">10+</option>' +
'</select>';
} else if (parseInt(this.value) > 9 && this.tagName.toLowerCase() === "select") {
template =
'<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number" value="'+this.value+'">';
}
if (template) {
$(this).replaceWith(template);
$('.qty-input option[value='+this.value+']').attr('selected', true);
$('.qty-input').change(updateControl);
}
}
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<select id="txtQuantity" name="txtQuantity" class="qty-input">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10+</option>
</select>
check this out what I am telling Fiddle Demo
$(".select").on('click',function(){
if(isNaN($(this).val())){
$(this).addClass("hide");
$(".more").removeClass("hide");
$(this).removeAttr("name","quantity");
$(".more").attr("name","quantity");
} });
You may refine code to your purpose.
For example I am adding field after selecting the Parent then insert child field , I want to submit a form when select list is ended or select is on last child how to submit after I added all fields and if I have no child of select then submit
<script type="text/javascript">
var children = $H(<?php echo json_encode($tree['children']) ?>);
function showCat(obj, level) {
var catId = obj.value;
level += 1
if ($('cat_container_' + level)) {
$('cat_container_' + level).remove();
}
if (children.get(catId)) {
var options = children.get(catId);
var html = '<select id="cat_' + catId + '" onchange="showCat(this, ' + level + ')">';
for (var i = 0; i < options.length; i++) {
html += '<option value="' + options[i].entity_id + '">' + options[i].name + '</option>';
}
html += '</select>';
html = '<div id="cat_container_' + level + '">' + html + '</div>';
$('sub_cat').insert(html);
}
}
Here is my form i m using onchange="this.form.submit()"
<form id="search_mini_form" action="<?php echo $catalogSearchHelper->getResultUrl() ?>" method="get">
<select id="first_cat" name="<?php echo $catalogSearchHelper->getQueryParamName() ?>" value="<?php echo $catalogSearchHelper->getEscapedQueryText() ?>" onchange="showCat(this,2);this.form.submit()">
<?php foreach ($tree['first'] as $cat): ?>
<option value="<?php echo $cat->getId() ?>"><?php echo $cat->getName() ?> </option>
<?php endforeach ?>
</select>
<button type="submit" title="<?php echo $this->__('Search') ?>" class="button"><span><span><?php echo $this->__('Search') ?></span></span></button>
This code is adding field but it submit on first select i have a tree of select and i want to submit when its on last select
var strLastOptionSelected = $("select option:last-child").val();
$("select").change(function() {
if ($(this).children("option:selected").val() === strLastOptionSelected) {
alert("You have selected the last option");
//Submit code
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
hi i have a select tag and i need if i click on any option from my first select.=====>i will get his attribute for it in the second select
my example is
<select name="select" >
<?php
$a={java,c++,php,python}
for($i=0;$i<4;$i++)
echo'<option value="'($i+1).'">'.$a[$i].' </option>';
}?>
</select>
<select name="select2" >
<?php
$after={{'j','jj','jjj'},
{'c','cc','ccc'},
{'p','pp','ppp'},
{'y','yy','yyy'}};
for($i=0;$i<3;$i++)
echo'<option value="'($i+1).'">'.$after[here the value of first select][$i].' </option>';
}?>
</select>
for example now if i chose java i need the select2 j jj jjj
if i chose c++ from the first select i need in the select 2 c cc ccc
i think it can be happen in jquerybut i don't know how it can be
Given your example, a possible output would be:
<select name="selectCode" >
<option></option>
<option value="1">java</option>
<option value="2">c++</option>
<option value="3">php</option>
<option value="4">python</option>
</select>
<br />
<select name="select2" style="display: none;">
</select>
The JQuery you want is:
var after = {};
after[1] = {0:"j",1:"jj",2:"jjj"};
after[2] = {0:'c',1:'cc',2:'ccc'};
after[3] = {0:'p',1:'pp',2:'ppp'};
after[4] = {0:'y',1:'yy',2:'yyy'};
$(function(){
$("select[name='selectCode']").on("change", function(){
console.log("selectCode Changed: " + $(this).val());
$("select[name='select2']").html("");
for(var i = 0; i<3; i++){
$("select[name='select2']").append("<option value='" + (i+1) + "'>" + after[$(this).val()][i] + "</option>").show();
}
});
});
jsFiddle example: http://jsfiddle.net/Twisty/xc4rs09m/