i want to display a certain number of input tags for a form; this should depend on how many items a user dynamically selects that they want.
for example, if a user says they want 3 items. i want to display 3 input bars.
i am not clear of the best way to proceed with this. for example, i am able to determine how many items they select from the select options:
$(".howmany").change(function(){
var value = $(this).val();
}
but what is the correct way to proceed thereafter; do i dynamically render the exact number of input tags selected using a for each: or pre-display (but hide) all of the input tags and only show the exact number of input tags requested.
i would appreciate an example of how its been done . at the moment i am only able to hide the entire area. eg:
var requests = $("#howmany").val();
if (reqeusts < 1){
$('#reqeusts').hide();
}
else {
$('#reqeusts').show();
}
but i obviously need to be able to show individual form tags accordingly to the number the user selected.
hi again, i want to thank everyone for their answers.
i deeply sorry, but i forgot to mention that the reason for the confusion is that the values for the imput are dynamically fed from an array function.
public function arrayValues()
{
return $selection = array(
'0' => 'none' ,' 1' => '1 item' ,' 2' => '2 item' ,' 3' =>' 3 item' );
}
i then need to render one of the below imput select tags for each number of items selected.
<?php echo '
<select id="howmany" name="items[howmany]" />';
foreach ($arrayValues as $key => $value)
{
echo '<option value="' . $key .'">' . $value . '</option>';
}
echo'</select>';
?>
$(".howmany").change(function(){
var value = $(this).val(); // get the number of inputs
value = parseInt(value); // make sure it's an integer
htmlStr = "";
for (var i = 0; i < value; i++)
{
htmlStr += "Label " + i +" <input type='text'>";
}
$('.container').empty();
$('.container').append(htmlStr);
}
You need something like this:
$('button').click(function () {
$('div').empty().append(new Array(+$('input[type=number]').val()+1)
.join("<input type='text' placeholder='Type Something'/>"));
});
I hope this gives you an idea of how to solve your problem.
DEMO
Related
I am creating a reacting quiz that changes based on the answer you have selected using PHP and Javascript.
This is the working example of the radio button script that changes the innerHTML based on what answer you have selected. Using PHP to write the value as 'AQN20'
$(function () {
$("input[name=AQN2]:radio").click(function () {
if ($('input[value=AQN20]:checked').val()) {
document.getElementById("MCA2").innerHTML = "this is right";
}
else {
document.getElementById("MCA2").innerHTML = "this is wrong";
}
});
});
I am trying to replicate the same behaviour for checkboxes but consider multiple answers.
So, I have a PHP array where you type your answers.
$multipleCheckboxOptions = array(
'Option A',
'Option B',
'Option C',
'Option D'
);
I then create each answer as a checkbox option and assign the arrays Key to the Value. So in the example directly below, this would be the first option in the array (outputted HTML example).
<input type="checkbox" name="AQN1" class="checkbox Q1" value="0" id="0mcq">
I then have another array where you can select what the correct answers are.
$correctAnswerNumber = array(0,2)
In this instance, answer 1 and 3 would be the correct answers.
Below is where I am currently stuck for the checkbox on behaviour using PHP,
$(function () {
$("input[name=<?php echo $uniqueIDAnswer ?>]:checkbox").click(function () {
if ($('input[value=<?php echo $correctAnswerNumber?>]:checked').val()) {
document.getElementById("CA<?php echo $mcanumber?>").innerHTML = "<?php echo $correctAnswerDescriptionAnswer ?>";
}
else {
document.getElementById("CA<?php echo $mcanumber?>").innerHTML = "<?php echo $incorrectAnswerDescriptionAnswer ?>";
}
});
});
I need the [value=] tag ($correctAnswerNumber) to output 0 && 3
'input[value=<?php echo $correctAnswerNumber?>]:checked'
I hope I have explained this clearly enough! Sorry if it is confusing.
It should be RadioButtonGroup instead of CheckBoxGroups and also create one more variable which is call as Answer and where the true answer is placed set that radio button as Answer and make a logic answer is selected it will be ur right answer
I want mutliple radio buttons (number unknown, because they get created dynamcially) to have the same onClick or onChange event, whichever fits the best. I found examples for jQuery but not pure Javascript. Should i just loop trought all radio buttons on the form?
They get created in php like so:
//DB Connection already established
$sql = "SELECT * FROM users";
$results = $dbConnection->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch-assoc()){
echo "<li><input type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>";
}
}
else
{
echo "<p>No users found</p>";
}
How can i do that loop? Or is there any more common way of doing that?
If one of them get's clicked i want their value as a parameter for the event, in only one function.
Or Should i just add onclick=myfunction(this) into the php file?
I want multiple radio buttons (number unknown, because they get created dynamically) to have the same onClick or onChange event.
If one of them get's clicked i want their value as a parameter for the event, in only one function.
Let's assume that your PHP has rendered the list items and you have a common function called myFunction() which you want to use to log it's parameter to your console:
function myFunction(val){
console.log("The value is " + val);
};
Now if I understand you correctly, you want to run the above function whenever one of the rendered radio buttons are clicked and to pass the value of the value attribute of the radio button that was clicked as a parameter for the above function.
Firstly, you need to assigned all the rendered radio button in your list to a variable:
var x = document.querySelectorAll("li input");
Secondly, since x is a collection of objects (here, all the radio buttons rendered), you will now have to map through each item on x using forEach and assign a click listener on each radio button which runs the ClickItem()function passing it the item's defaultValue as a parameter val like this:
x.forEach(function(radio) {
radio.addEventListener('click', function() {
var val = this.defaultValue;
myFunction(val);
});
});
jsFiddle: http://jsfiddle.net/AndrewL64/2y6eqhb0/56/
However, if by value, you mean the content after the input tag but still inside the respective li tag, then you just need to make slight changes to the above code like this:
Firstly, to prevent the selector from querying li elements from other parts of the page, you need to wrapped your list items with a div or a ul having a unique ID like this:
<ul id="someList">
//create your list items here
</ul>
Secondly, you need to assigned all the rendered list items to a variable:
var x = document.querySelectorAll("#someList li");
Thirdly, similarly to what we did above, since x is a collection of objects (here, all the list items rendered), you will now have to map through each item on x using forEach and assign a click listener on each list item which runs the ClickItem()function passing it the item's innerText as a parameter val like this:
x.forEach(function(radio) {
radio.addEventListener('click', function() {
var val = this.innerText;
myFunction(val);
});
});
jsFiddle: http://jsfiddle.net/AndrewL64/2y6eqhb0/58/
Actually the JQuery make it easier, but you can do the same with pure JS.
the real concept is to capture the event bubbling, try this:
fatherElement => element that is not dynamic
fatherElement.addEventListener("click", function(event){
if(event.target.type == 'radio'){
//do something
}
});
Use this echo line instead yours:
echo "<li><input onchange='yourOnChange(event)' type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>";
I add onchange='yourOnChange(event)' there. And of course remember to add proper js function e.g function yourOnChange(e) { console.log(e); } to your web page.
Or Should i just add onclick=myfunction(this) into the php file?
Yes, you can do that. In that case code will be;
<li><input onclick='myclick('". $row['E-Mail'] ."')' type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>"
Now in JS code myclick(email) function can handle anything with email argument.
Pure JS solution:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'radio') {
if(inputs[i].checked)
{
//if radio button is checked
myClick(inputs[i].id, 'checked') //you can get anything apart from id also
}
else
{
//if radio button is not checked
myClick(inputs[i].id, 'unchecked') //you can get anything apart from id also
}
}
}
myClick(id, stat)
{
//YAY!! I have got the id
}
You can do a for of loop if you have querySelectorAll.
Here is an example:
const radios = document.querySelectorAll('input[type=radio]');
for (const element of radios ) {element.addEventListener('click', function(event) {
console.log(event.currentTarget)
})
}
Using pure JS you can select your radio buttons and add event listeners like so:
const radios = document.querySelectorAll('input[type=radio]');
radios.forEach(radio => radio.addEventListener('change', e => {
// radio is your radio button element
});
Same with jQuery:
$('input[type=radio]').change(() => {
//your code goes here
});
I am echoing out a form (foreach) from my filemaker records which will result in the items ID, Name, a Checkbox and then an image.
In my understanding i will have to use classes or the elements will all have the same id.
My Code;
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo '"'.$id.'"<br>';
echo $name.'<br>';
echo '<input type="checkbox" class="check" value="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'">';
echo '<div class="pics">';
echo '<img style="width:200px;" src="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'"><br>';
echo '<hr>';
echo '</div>';
}
Which results in a page full of the records, a checkbox and the relating image.
I wish to only show these images when the checkbox is checked but cannot find a solution, i have tried many jquery scripts, to no avail.
The images will then populate the next page as a pdf to be printed.
I am hoping not to have to grab the checkbox's values as an array to then use the get method with 100's of if statements but cant see another way ?
The jquery ive used.
$(document).ready(function () {
$('.pics').hide();
$('.check').click(function () {
$('pics').show;
});
$('.pics').hide;
});
and
$(function() {
$(".check").click(function(e) {
e.preventDefault();
$('.pics').hide();
$('.pics').show();
});
});
Plus many similar alternatives.
Is there something obvious i am missing ?
Query to filemaker method;
I have changed the path field to a calculated value which works great, thank you, although with 1000's of records, i would need lots of php code to echo the checkbox's to the website and lots more to be able to edit them from the website.
I have done this previously with the value held within the checkbox in filemaker.
$sesame = $print->getField('Allergens::Allergens[11]'); if ($sesame == "Sesame") { $sesame = "checked" ;} else if ($sesame !== "Sesame") {$sesame = "" ;}
This displays the checkbox synced with filemaker.
if ($_POST['Sesame'] == 'Sesame'){ $a_sesame = 'Sesame';} else { $a_sesame = 'No Sesame'; }
This is sent as a variable to my script.
if($a_sesame == "Sesame"){$contains_sesame = "Yes";} else { $contains_sesame = "No";}
This grabs the new value from the form.
Which all work great, but then i am writing a script in filemaker too to enable the to and from of the different names for each checkbox state.
which is for this part 120 lines long, this is a sample which i have to repeat for each repetition of this field.
Set Variable [ $sesame; Value:GetValue ( Get ( ScriptParameter ) ; 11 ) ]
If [ $sesame = "Sesame" ]
Set Field [ Allergens::Allergens[11]; "Sesame" ] Commit Records/Requests
[ Skip data entry validation; No dialog ]
Else If [ $sesame = "No Sesame" ]
Clear [ Allergens::Allergens[11] ] [ Select ]
Commit Records/Requests
[ Skip data entry validation; No dialog ]
Refresh Window
[ Flush cached join results; Flush cached external data ]
End If
This would be far too large to write for so many records, just for these 14 fields used 120 in filemaker and 400 plus in the php.
I am not 100% sure what you are trying to do but this should work. First add an extra div that closes input and div pics like below.
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo <<<TEXT
'{$id}'<br>
{$name}<br>
<div>
<input type='checkbox' class='check' value='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'>
<div class='pics'>
<img style='width: 200px;' src='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'><br>
<hr>
</div>
</div>
TEXT;
}
then change your java to this
$(document).ready(function() {
$(".pics").hide();
$(".check").click(function() {
$(this).siblings().toggle();
});
});
well I hope this helps
Another alternative would be to set up a simple calculated container field in FileMaker, with a calculated value of:
If ( checkbox; imageField )
This would only pass the image when the checkbox was ticked for a record. This should be faster than handling this in JavaScript, since you'd be limiting the number of images being sent over the wire.
Note: For performance, you might try this with this calculated container field stored and unstored. I suspect stored v unstored should make little difference, in which case I'd suggest leaving this unstored to minimize disk space consumed.
You can use the toggle()function:
$(function() {
$('.pics').hide();
$(".check").is(':checked',function(e) {
e.preventDefault();
$('.pics').toggle();
});
});
I want to implement a search box same as this, at first, just first dropdown list is active once user selects an option from the first dropbox, the second dropdown box will be activated and its list will be populated.
<s:select id="country" name="country" label="Country" list="%{country} onchange="findCities(this.value)"/>
<s:select id="city" name="city" label="Location" list=""/>
Jquery chained plugin will serve your purpose,
https://plugins.jquery.com/chained/
usage link - http://www.appelsiini.net/projects/chained
this plugin will chain your textboxes.
Try this code where based on your needs you have to populate it with your options:
var x;
$('#pu-country').on('change', function () {
if (this.value != '0') {
$('#pu-city').prop('disabled', false);
$('#pu-city').find("option").not(":first").remove();
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
switch (this.value) {
case 'A':
x = '<option value="A.1">A.1</option><option value="A.2">A.2</option><option value="A.3">A.3</option>'
}
$('#pu-city').append(x)
} else {
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
$('#pu-city').prop('disabled', true);
$('#pu-city').val("Choose");
}
});
$('#pu-city').on('change', function () {
if (this.value != '0') {
$('#pu-location').prop('disabled', false);
$('#pu-location').find("option").not(":first").remove();
switch (this.value) {
case 'A.1':
x = '<option value="A.1.1">A.1.1</option><option value="A.1.2">A.1.2</option><option value="A.1.3">A.1.3</option>'
break;
case 'A.2':
x = '<option value="A.2.1">A.2.1</option><option value="A.2.2">A.2.2</option><option value="A.2.3">A.2.3</option>'
break;
case 'A.3':
x = '<option value="A.3.1">A.3.1</option><option value="A.3.2">A.3.2</option><option value="A.3.3">A.3.3</option>'
break;
}
$('#pu-location').append(x)
} else {
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
}
});
I have also set up and a demo to see the functionallity with more options.
FIDDLE
Your code should be something like this:
$(country).change(function(){
var l=Document.getElementByID("country");
for(i=0;i<=l.length;i++)
{
if(l.options[i].selected?)
{
text_array=[HERE YOU NEED TO ADD THE CITIES OF l.options[i].text];
val_array=[HERE YOU NEED TO ADD THE VALUES OF THECITIES OF l.options[i].text];
}
}
var c=Document.getElementByID("city");
c.options.text=[];
c.options.value=[];
//You now should have an empty select.
c.options.text=text_array ;
c.options.value=val_array ;
});
As I don't know, what kind of DB you use, to have the cities connected to their countrys, I can't tell you, what to put into the uppercase text...
Ciao j888, in this fiddle i tried to reconstruct the same system as the site you provided the link
the number of states cityes and locality is less but the concept remains the same
If you want to add a new state you must enter a new html options in select#paese with an id.
Then you have add in obj.citta a property with this id name and an array of cityes for a value.
The same thing for obj.localita where you will create an array of arrays.
The jQuery code you need is
<script type="text/javascript">
$(document).ready(function(){
var obj={
citta:{ //value is the same of option id
albania:['Durres','Tirana'],
austria:['Vienna','innsbruck','Graz'],
},
localita:{//for every city create a sub array of places
albania:[['località Durres1','località Durres 2'],['località Tirana','località Tirana 2']],
austria:[['località Vienna','località Vienna 2'],['località innsbruck','località innsbruck 2'],['località Graz','località Graz 2','località Graz 3']],
}
}
$('#paese').on('change',function(){
$('#località').attr('disabled','disabled').find('option').remove()
var quale=$(this).find('option:selected').attr('id')
var arr=obj.citta[quale]
if(arr){
$('#citta').removeAttr('disabled')
$('#citta option.added').remove()
for(i=0;i<arr.length;i++){
$('<option class="added">'+arr[i]+'</option>').appendTo('#citta')
}
}
})
$('#citta').on('change',function(){
var ind=($(this).find('option:selected').index())-1
var quale=$('#paese').find('option:selected').attr('id')
var arr=obj.localita[quale][ind]
if(arr){
$('#località').removeAttr('disabled')
$('#località option.added').remove()
for(i=0;i<arr.length;i++){
$('<option class="added">'+arr[i]+'</option>').appendTo('#località')
}
}
})
})
</script>
If this solution does not suit your needs, i apologize for making you lose time.
Hi i have done this for license and its dependent subject in yii 1.
The license dropdown
//php code
foreach($subject as $v) {
$subj .= $v['licenseId'] . ":" . $v['subjectId'] . ":" . $v['displayName'] . ";";
}
Yii::app()->clientScript->registerScript('variables', 'var subj = "' . $subj . '";', CClientScript::POS_HEAD);
?>
//javascript code
jQuery(document).ready(function($) {
//subject. dependent dropdown list based on licnse
var ty, subjs = subj.split(';'), subjSel = []; //subj register this varible from php it is
for(var i=0; i<subjs.length -1; i++) { //-1 caters for the last ";"
ty = subjs[i].split(":");
subjSel[i] = {licId:ty[0], subjId:ty[1], subjName:ty[2]};
}
//dropdown license
jQuery('#license#').change(function() {
$('#add').html(''); //clear the radios if any
val = $('input[name="license"]:checked').val();
var selectVals = "";
selectVals += '<select>';
for(var i=0; i<subjSel.length; i++) {
if(subjSel[i].licId == val) {
if(subjSel[i].subjId *1 == 9) continue;
selectVals += '<option value="'+subjSel[i].subjId+'">'+subjSel[i].subjName+'</option>';
}
}
selectVals += '</select>';
$("#subject").html(selectVals);
});
});
You seem to be asking two questions:
QUESTION 1. How to have a disabled select box (the second and third select boxes in the case of your example) which is activated upon the selection of an option from the first select box.
ANSWER 1:
simply use the disabled=true/false as below...
<select id="country" name="country" label="Country" onchange="document.getElementById('city').disabled=false; findCities(this.value)"/>
<select id="city" name="city" label="Location" disabled=true/>
NOTE: I changed "s:select" to "select" on the basis that your question does not make reference or tag the Struts framework that uses this syntax.
QUESTION 2: How to populate the second select box when a selection is made in the first.
ANSWER 2: There are many ways to do this, and the choice depends on where you have the data to populate the lists with. In the case of your Rentalcars example, if you chose Barbados, the browser sends an ajax GET request to "http://www.rentalcars.com/AjaxDroplists.do;jsessionid=5DCBF81333A88F37BC7AE15D21E10C41.node012a?country=Barbados&wrapNonAirports=true" -try clicking on this link and you will see what that request is sending back. This '.do' address is a server side file of a type used with the Struts framework I mentioned above.
A more conventional approach, which would be included in your function findCities(country)would be to send an AJAX request to a PHP script which queries a database and sends back an array of place names to the browser. The AJAX javascript code includes instructions as to what to do with the response. Without knowing more about where you want to store your list, giving an example of this would most likely not be useful.
Alternatively, the whole list of places could be included in the javascript script as an array (as demonstarated by Devima, above), in a text document on the server as comma separated values, or you could save it to a browser database like WebSQL or IndexedDB if offline use would be useful.
When you have got your list, probably as an array of values, you could save the array as a variable eg. var cities=result (in the case of a simple ajax request). You will then need to iterate through cities, for example
for (var i = 0; i < cities.length; i++){
var place=cities[i];//an individual city name
document.getElementById("city").innerHTML+="<option value='" + place + "'>" + place + "</option>";//adds an 'option' with the value being the city name and the text you see being the city name
}
IMO this is the base case AngularJS was designed to completely alleviate. Check it out!
I have this code:
while($row = mysql_fetch_array($res)) {
$name = $row['advertiser'];
$id = $row['id'];
if($row['id'] % 4 == 1 || $row['id'] == 1)
{
echo "<tr>";
}
if($row['availability'] == 0)
{
$td = "<td id='green'>";
}
if($row['availability'] == 1)
{
$td = "<td id='grey'>";
}
if($row['price'] == 0)
{
mysql_query("UPDATE booklet SET availability = 0 WHERE id = '$id'");
}
echo $td . $row['id'] . "<br/><p style='font-size: 6pt;'>" . $name[0] . "<p><img src=" . $row['image'] . "></td>";
if($row['id'] % 4 == 0)
{
echo "</tr>";
}
}
It creates a table. What I want to do is this: if you click on a td, I want to pass the value of that td, for example - the number one (1), if you clicked on the first td - I want to pass this value over to a hidden input so I may later use it elsewhere.
The table looks fine. I know what to do when I have the value in a hidden input. I just need to be able to have the table, when I click on a td, to pass the value over. Or to do anything. onClick doesn't work. Even the absolute simplest isolated JQuery statements don't even come close to parsing. The most complex Javascript that actually has worked on this page is a document.write(). Everything else stumps any known browser.
So, using absolutely any methods, is it a possibility, within the realm of current technology, to have code that does what I want?
Again, I need to have a table cell, when clicked on, pass a variable to a hidden input. I've tried everything.
You'll need to add the click event with JQuery and then use Jquery to set the value... Something like this should work.
$(function() {
$("table#mytable td").mouseover(function() {
//The onmouseover code
}).click(function() {
//The onclick code
$("#hiddenInputID").val(text);
});
});
<td onclick="document.forms[0]['nameofhiddenfield'].value = this.id"> ... </td>
Try to validate your html, you might have mismatched quotes/square brackets somewhere, which breaks Javascript.