How can I get special web elements in appending function with Jquery? - javascript

I have a problem with this, when I have a bottom function to appending some web elements, like this:
var index = 0;
$("#addGift").click(function () {
var gift = "<ul id=\"ul\">\n" +
" <li>\n" +
" <label>Gift Type1</label>\n" +
" <select name=\"giftType\">\n" +
" <option value=\"coin\">coin</option>\n" +
" <option value=\"album\">album</option>\n" +
" <option value=\"vip\">vip</option>\n" +
" </select>\n" +
" </li>\n" +
" <li>\n" +
" <label>Num</label>\n" +
" <input type=\"number\" name=\"num\">\n" +
" </li>\n" +
" <li>\n" +
" <label>Time</label>\n" +
" <input name=\"time\" class=\"easyui-datebox\" data-
options=\"sharedCalendar:'#cc'\">\n" +
" </li>\n" +
" <li>\n" +
" <label>Unit</label>\n" +
" <select name=\"unit\">\n" +
" <option value=\"day\">day</option>\n" +
" <option value=\"month\">month</option>\n" +
" </select>\n" +
" </li>\n" +
" <li>\n" +
" <label>Gift Type2</label>\n" +
" <select name=\"giftType\">\n" +
" <option value=\"coin\">coin</option>\n" +
" <option value=\"album\">album</option>\n" +
" <option value=\"vip\">vip</option>\n" +
" </select>\n" +
" </li>\n" +
" <li>\n" +
" <label>Num</label>\n" +
" <input type=\"number\" name=\"num\">\n" +
" </li>\n" +
" <li>\n" +
" <label>Time</label>\n" +
" <input name=\"time\" class=\"easyui-datebox\" data-
options=\"sharedCalendar:'#cc'\">\n" +
" </li>\n" +
" <li>\n" +
" <label>Unit</label>\n" +
" <select name=\"unit\">\n" +
" <option value=\"day\">day</option>\n" +
" <option value=\"month\">month</option>\n" +
" </select>\n" +
" </li>\n" +
" </ul>"
$("#giftTable").append(gift);
index++;
});
I had try many ways to get that web elements like name='time' or name='unit' to do show or hide action, but it doesn't work. Because I didn't get that elements correctly.
So how can I get special web elements in appending function with Jquery?

welcome to stack overflow.
ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.
A template literal is delimited by backticks:
var index = 0;
$("#addGift").click(function () {
var gift = `<ul id="ul">
<li>
<label>Gift Type1</label>
<select name="giftType">
<option value="coin">coin</option>
<option value="album">album</option>
<option value="vip">vip</option>
</select>
</li>
<li>
<label>Num</label>
<input type="number" name="num">
</li>
<li>
<label>Time</label>
<input name="time" class="easyui-datebox" data-options="sharedCalendar:'#cc'">
</li>
<li>
<label>Unit</label>
<select name="unit">
<option value="day">day</option>
<option value="month">month</option>
</select>
</li>
<li>
<label>Gift Type2</label>
<select name="giftType">
<option value="coin">coin</option>
<option value="album">album</option>
<option value="vip">vip</option>
</select>
</li>
<li>
<label>Num</label>
<input type="number" name="num">
</li>
<li>
<label>Time</label>
<input name="time" class="easyui-datebox" data-options="sharedCalendar:'#cc'">
</li>
<li>
<label>Unit</label>
<select name="unit">
<option value="day">day</option>
<option value="month">month</option>
</select>
</li>
</ul>`;
$("#giftTable").append(gift);
index++;
});

Related

Jquery adding validate rules on select dynamically created

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

PHP post with dynamic entries created in JS

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>

For loop ending unexpectedly

I'm having an issue with an assignment.
My for loop doesn't seem to run and I'm not sure what I've done wrong.
The variable dailyText prints "Weather Forecast" in a table but doesn't seem to enter the for loop. I'm not sure if this is a scoping issue or what's happening.
The script is supposed to take a number from a form option and create a table with that many rows.
Any help would be greatly appreciated!
function dailyInfo() {
var dailyText = "";
var numberDays = document.getElementById("numberDays").value; //https://stackoverflow.com/questions/23982774/turn-html-form-input-into-javascript-variable
dailyText += "<table class='table'><tr><th>Weather Forecast</th></tr>";
for (var i = 0; i < numberDays; i++) {
dailyText += "<tr><td>Day: " + (i + 1) + "</td>";
dailyText += "<td>" + dailyJsonObject.list[i].temp.min + "&#8451</td>";
dailyText += "<td>" + dailyJsonObject.list[i].temp.max + "&#8451</td>";
dailyText += "<td>" + dailyJsonObject.list[i].weather[0].description + "<img src ='http://openweathermap.org/img/w/'" + dailyJsonObject.list[i].weather[0].icon + ".png' /></td>";
}
document.getElementById("demo").innerHTML = dailyText;
dailyText += "</tr></table>";
}
<form id="numberDay">
<label id='numberDays'>Number of days requested</label>
<select name='numberDays'>
<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>
</select>
<button type="button" onclick="dailyInfo()">Submit</button>
</form>
</div>
<div id='demo'>
<table id="tableDaily"></table>
</div>
You have named the label with the id required for the numberDays. This means the loop was using the label value not the actual input as expected.
See below for alteration:
<form id="numberDay">
<label id='numberDays_label'>Number of days requested</label>
<!-- the select needs the id so the JS code can grab it!-->
<select name='numberDays' id="numberDays">
<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>
</select>
<button type="button" onclick="dailyInfo()">Submit</button>
</form></div>
<div id='demo'>
<table id="tableDaily"></table></div>
You say:
var numberDays = document.getElementById("numberDays").value;
But actually the element you are getting is the label:
<label id='numberDays'>
So numberDays has actually the value undefined then.
Instead, you should do:
<label for='numberDays'>
and then:
<select name='numberDays' id='numberDays'>
That should actually at least start the loop. And then the label > select relationships is actually working, for example you can click now also the label to focus on the select.
Access a selected option:
HTML
<select name="" id="mySelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
</select>
JavaScript
var select = document.getElementById("mySelect"),
selectedOption = select.options[select.selectedIndex].text;
Get selected option text with JavaScript
In total (commented stuff)
function dailyInfo() {
var dailyText = "";
var numberDays = document.getElementById("numberDays");
numberDays = numberDays.options[numberDays.selectedIndex].text;
dailyText += "<table class='table'><tr><th>Weather Forecast</th></tr>";
for (var i = 0; i < numberDays; i++) {
dailyText += "<tr><td>Day: " + (i + 1) + "</td>";
dailyText += "<td>" + /*dailyJsonObject.list[i].temp.min +*/ "&#8451</td>";
dailyText += "<td>" + /*dailyJsonObject.list[i].temp.max +*/ "&#8451</td>";
dailyText += "<td>" + /*dailyJsonObject.list[i].weather[0].description*/ +"<img src ='http://openweathermap.org/img/w/'" + /*dailyJsonObject.list[i].weather[0].icon +*/ ".png' /></td>";
}
document.getElementById("demo").innerHTML = dailyText;
dailyText += "</tr></table>";
}
<form id="numberDay">
<label>Number of days requested</label>
<select id='numberDays' name='numberDays'>
<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>
</select>
<button type="button" onclick="dailyInfo()">Submit</button>
</form>
<div id='demo'>
<table id="tableDaily"></table>
</div>

Javascript go to the next line

First off, I'm sure there's some obvious answer to this, but I'll ask still.
So I have this project where the user is rolling dice, and writing what the dice is for and what is being done.
It works through html forms and the javascript prints the results without refreshing the page. I got all that working.
My current issue is that I want the result of the code to move on to the next line, and continue on when you click 'submit' again.
$( "#modTool" ).submit(function( event ) {
event.preventDefault();
console.log($(this).serialize());
var a = document.getElementById("modTool").elements.namedItem("user").value;
var b = document.getElementById("modTool").elements.namedItem("actionTaken").value;
var c = document.getElementById("modTool").elements.namedItem("target").value;
var amount = document.getElementById("modTool").elements.namedItem("amountOfDice").value;
var sides = document.getElementById("modTool").elements.namedItem("typeOfDice").value;
var d = document.getElementById("modTool").elements.namedItem("bonus").value;
var diceRoll = rollDice(amount, sides);
var display=document.getElementById("Prompt");
display.innerHTML = "> " + a + " uses " + b + " towards " + c + "<br />" + "> " + diceRoll + " Bonus " + d;
});
https://i.gyazo.com/fe3ffa835ed1acf41c08c7f6fe46ea93.png
It needs to both go to the next line, when I click 'submit' again, as well as having a scrollbar.
Any ideas?
Use this line:
display.innerHTML += "> " + a + " uses " + b + " towards " + c + "<br />" + "> " + diceRoll + " Bonus " + d + "<br /><br />";
Instead of:
display.innerHTML = "> " + a + " uses " + b + " towards " + c + "<br />" + "> " + diceRoll + " Bonus " + d;
display.scrollTop = display.scrollHeight;
Add overflow to your #Prompt like this:
#Prompt {
border-style: groove;
height: 400px;
max-width:98%;
width:auto;
position:relative;
overflow-y: auto;
}
See working example:
function rollDie(sides) {
if(!sides) sides = 6;
with(Math) return 1 + floor(random() * sides);
}
function rollDice(number, sides) {
var total = 0;
while(number-- > 0) total += rollDie(sides);
return total;
}
$( "#modTool" ).submit(function( event ) {
event.preventDefault();
console.log($(this).serialize());
var a = document.getElementById("modTool").elements.namedItem("user").value;
var b = document.getElementById("modTool").elements.namedItem("actionTaken").value;
var c = document.getElementById("modTool").elements.namedItem("target").value;
var amount = document.getElementById("modTool").elements.namedItem("amountOfDice").value;
var sides = document.getElementById("modTool").elements.namedItem("typeOfDice").value;
var d = document.getElementById("modTool").elements.namedItem("bonus").value;
var diceRoll = rollDice(amount, sides);
var display=document.getElementById("Prompt");
display.innerHTML += "> " + a + " uses " + b + " towards " + c + "<br />" + "> " + diceRoll + " Bonus " + d + "<br /><br />";
display.scrollTop = display.scrollHeight;
});
* {
font-family: Helvetica, Arial, sans-serif;
}
#wrapper {
max-width:98%;
width:auto;
margin:auto;
background-color: #fff;
}
#Prompt {
border-style: groove;
height: 400px;
max-width:98%;
width:auto;
position:relative;
overflow-y: auto;
}
#Buttons {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="wrapper">
<div id="Prompt">
<br />
<!-- <p id="diceRoll">
</p>
-->
</div>
<br />
<div ="Buttons">
<form id="modTool" method="POST" action="">
<table>
<tr>
<td>
<td><b>USER</b> </td>
<td><select name="user" id="User">
<option id="PC10">0</option>
<option id="PC11">1</option>
<option id="PC12">2</option>
<option id="PC13">3</option>
<option id="PC14">4</option>
<option id="PC15">5</option>
<option id="PC16">6</option>
<option id="PC17">7</option>
<option id="PC18">8</option>
<option id="PC19">9</option>
<option id="PC110">10</option>
</select></td>
</td>
<td>
<td><b>ACTION TAKEN</b> </td>
<td><input type="text" name="actionTaken"></input>
</td>
<td>
<td><b>TARGET</b> </td>
<td><select name="target" id="target">
<option id="PC20">0</option>
<option id="PC21">1</option>
<option id="PC22">2</option>
<option id="PC23">3</option>
<option id="PC24">4</option>
<option id="PC25">5</option>
<option id="PC26">6</option>
<option id="PC27">7</option>
<option id="PC28">8</option>
<option id="PC29">9</option>
<option id="PC210">10</option>
</select></td>
</td>
</tr>
<tr>
<td>
<td><b>DICE SIDES</b> </td>
<td><select name="typeOfDice" id="typeOfDice">
<option id="D20">20</option>
<option id="D100">100</option>
</select></td>
</td>
<td>
<td><b>AMOUNT OF DICE</b>
<td><select name="amountOfDice" id="amountOfDice">
<option id="1Dice">1</option>
<option id="2Dice">2</option>
<option id="3Dice">3</option>
<option id="4Dice">4</option>
<option id="5Dice">5</option>
<option id="6Dice">6</option>
<option id="7Dice">7</option>
<option id="8Dice">8</option>
<option id="9Dice">9</option>
<option id="10Dice">10</option>
</select></td>
</td>
<td>
<td><b>BONUS</b> </td>
<td><select name="bonus" id="bonus">
<option id="plus0">0</option>
<option id="plus1">+1</option>
<option id="plus2">+2</option>
<option id="plus3">+3</option>
<option id="plus4">+4</option>
<option id="plus5">+5</option>
<option id="plus6">+6</option>
<option id="plus7">+7</option>
<option id="plus8">+8</option>
<option id="plus9">+9</option>
<option id="plus10">+10</option>
<option id="Minus1">-1</option>
<option id="Minus2">-2</option>
<option id="Minus3">-3</option>
<option id="Minus4">-4</option>
<option id="Minus5">-5</option>
<option id="Minus6">-6</option>
<option id="Minus7">-7</option>
<option id="Minus8">-8</option>
<option id="Minus9">-9</option>
<option id="Minus10">-10</option>
</select></td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" name="submitRound" id="submit"></input>
</td>
<td>
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
EDIT:
Added overflow and made it autoscroll to bottom.

How to not lose the css while appending html to an element?

I am using bootstrap chosen to render dropdown menu.When I use the following code the rendering works fine.
<div class="row">
<div class="col-lg-3">
<select data-placeholder="Choose a Country" class="chosen-select chosenContainer" tabindex="2">
<option value=""></option>
<option value="United States">United States</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Albania">Albania</option>
<option value="Algeria">Algeria</option>
<option value="American Samoa">American Samoa</option>
</select>
</div>
</div>
Problem occurs when I append the above code to a div ,all the css is lost and a ordinary dropdown menu is displayed.
function populate()
{
var str=" <div class=\"row\">\n" +
" <div class=\"col-lg-3\" " +
" <select data-placeholder=\"Choose a Country\" class=\"chosen-select chosenContainers\" tabindex=\"2\">\n" +
" <option value=\"\"></option>\n" +
" <option value=\"United States\">United States</option>\n" +
" <option value=\"United Kingdom\">United Kingdom</option>\n" +
" <option value=\"Afghanistan\">Afghanistan</option>\n" +
" <option value=\"Albania\">Albania</option>\n" +
" <option value=\"Algeria\">Algeria</option>\n" +
" <option value=\"American Samoa\">American Samoa</option>\n" +
"\n" +
" </select>\n" +
" </div>\n" +
" </div>";
var elementDiv=document.getElementById("dynamicTag");
$("#dynamicTag").append(str);
}
How to not lose the css while appending html to an element?
Are you sure the html you write is correct ?
there's a missing closing > here :
" <div class=\"col-lg-3\" " +
Also you might want to write like this instead :
'<div class="col-lg-3"> '
You don't have to escape double quotes if they are inside single quotes (and vice-versa)

Categories