I'm working on a project for school that involve converting a form into HTML. At one point there is a drop down that asks if you are applying to be a TA or a PLA. When selected, I want a new text box to appear below that drop down. Here is what I have:
This is the dropdown data in my controller:
$data['selection'] = array("TA (Graduate Student)", "PLA (Undergraduate)");
Here is what is in the view:
<label for="studentSelection">What position are you applying for?
<?php echo Form::select(array( 'name'=> 'position', 'id' => 'position', 'class' => 'form-control', 'data' => $data['selection']));?>
</label>
This is what I'm attempting:
$("#position").change(function() {
//one selection is 1, the other is 0.
if ($("#position").val() == 1){
var row = $("<div class='row' id='row_position></div>");
var year = $('<div class = "col-md-6"></div>');
var position = $('<input type = "text", id="position1", name="position1" class="form-control"></input>');
$("#position").append(row);
row.append(year);
year.append(position);
//alert works when PLA is selected.
//alert("hello");
}
else {
//something else
}
I can't quite figure it out
I tried to fix the errors in your code: https://jsfiddle.net/840xyrL7/1/
<select id='position'>
<option value="1">Item1</option>
<option value="2">Item2</option>
</select>
$("#position").change(function() {
//one selection is 1, the other is 0.
if(this.selectedIndex === 1){
var row = $("<div class='row' id='row" + this.selectedIndex + "'></div>");
var year = $('<div class = "col-md-6"></div>');
var position = $('<input placeholder="Your text" type="text" id="position' + this.selectedIndex + '" name="position' + this.selectedIndex + '" class="form-control"></input>');
year.append(position);
row.append(year);
$("#position").after(row);
}
});
Here are the lessons learned for you:
Do not put comma between the attributes: type = "text", id=
Be careful about closing quotes: id='row_position></div>
Do not use append if you want to add a new control next to another control: $("#position").append(row);, instead use .after()
<div class='row' id='row_position></div>
You're missing a closing single quote for id, which is probably breaking everything. Try replacing that with
<div class='row' id='row_position'></div>
Related
I'm a hobbyist on my first project. In a form, oranizers can select multiple events in a collection select. I want these events to be available as choices in an array field checkbox collection further down in the same form.
First, organizer selects the events:
<%= f.input :events, collection: #organizer.events.order(:start_time).reverse, label_method: :event_name_and_date, input_html: {multiple: true, id: "event_select"} %>
Then, this checkbox collection field (and others like it in the form) should dynamically update with the previously selected events as options, so the ids of the checked off events get sent in the param array.
<%= f.input :events_to_include_in_event_pass_1, :collection => ["(previously selected events", "etc"], :as => :check_boxes, include_hidden: false, :input_html => {:multiple => true, id: "event_pass_select"} %>
I've got an ajax:
$('#event_select').on('change', function(){
var grab_events = $('#event_select').val();
var hpeData = '{"hpe": "' + grab_events + '"}';
$.ajax({
type: 'post',
url:'/events/get_the_e',
dataType:'json',
contentType:'application/json',
data: hpeData,
success:function (data) {
... $("document.forms["eventForm"]["events_to_include_in_event_pass_1"].collection_value(?)").update_with('data.hpe.each.event_name_... and_id_somehow_gets_added')
}
});
}
which brings back the instances selected in the first collection field, but I don't know how to dynamcially change #event_pass_select collection with these instances. ... is this even possible? Or is there some general better way to set something like this up?
Don't need an ajax call -- that's taking the data from the browser, sending it back to the server, then updating the browser.
A little jQuery will do the trick. Read through the selected options and use them to fill the desired input. Something like this...
$('#event_select').on('change', function(){
$("#event_pass_select").empty();
$("#event_select option:selected").each(function() {
var val = $(this).val();
var text = $(this).html();
$("#event_pass_select").append( $("<option>")
.val(val)
.html(text)
);
});
});
Change '#event_pass_select' to the appropriate control id on your form.
I didn't realize the input_html was in fact working, it just applied the id to each checkbox, instead of the whole input. I figured that out by clicking 'edit as html' in ctrl c. I also saw all the html that makes up each checkbox, and thought I would try putting all that in there, instead of just option, and it worked. These are probably a result of simpleform? I appreciate the help dbugger.
$('#event_select').on('change', function(){
var asdf = 1;
$("#event_select option:selected").each(function() {
var val = $(this).val();
var text = $(this).html();
if (asdf === 1) {
$(".festival_multipass_ticket_1_hpe span").empty();
$(".festival_multipass_ticket_1_hpe").append( $('<span class="checkbox"><label for="festival_multipass_ticket_1_hpe_' + asdf + '"><input class="check_boxes optional" type="checkbox" value="' + val + '" name="festival[multipass_ticket_1_hpe][]">' + text + '</label></span>')
);
} else {
$(".festival_multipass_ticket_1_hpe").append( $('<span class="checkbox"><label for="festival_multipass_ticket_1_hpe_' + asdf + '"><input class="check_boxes optional" type="checkbox" value="' + val + '" name="festival[multipass_ticket_1_hpe][]">' + text + '</label></span>')
);
}
asdf += 1;
});
I am trying to create an dynamic order form using Jquery and PHP and got stuck. I have a Jquery code that onclick adds a new set of fields. Also in that jquery code I apply some style and jquery to one of the fields. Its an Multiselect, Searchable dropdown list.
Problem here however. I can apply this style so that it has the search bar etc. to the first one. the ones after are just random multilists with no vallues or searchbar.
Here is my code:
$(document).ready(function() {
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
//THIS WORKS!!
var arrayFromPHP = ['foo', 'bar'];//<?php echo json_encode($a); ?>;
$("#country" + x).select2({
data: arrayFromPHP
});
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
//THIS DOESNT WORK!!
var arrayFromPHP = ['foo', 'bar'];//<?php echo json_encode($a); ?>;
$("#country" + x).select2({
data: arrayFromPHP
});
$(wrapper).append('' +
'<div>' +
'<select id="country'+ x +'" multiple="multiple" style="width:300px;">' +
'</select>' +
'Remove' +
'</div>' +
'<div><input type="number" name="quantity'+ x +'" min="1" max="10">Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<div class="input_fields_wrap">
<form method="post"><input type="submit" value="Add item" class="add_field_button"></form>
<div>
<select id="country1" multiple="multiple" style="width:300px;">
<!-- Dropdown List Option -->
</select>
</div>
</div>
So in the Jquery I put 2 comments in caps rage to mark what I mean that doesnt work.
Screenshots:
This on first sight
When I click in the multiselect tab this works.
Picture speaks for itself. just messed up and if I click it nothing happends.
You're initializing select2 before the HTML element exists:
$("#country" + x).select2({
data: arrayFromPHP
});
$(wrapper).append('' +
'<div>' +
'<select id="country'+ x +'" multiple="multiple" style="width:300px;">' +
'</select>' +
'etc...');
The select2 line should come AFTER you create the element with the append method. Try this (note that I didn't copy the whole text: this is just illustrative):
$(wrapper).append('' +
'<div>' +
'<select id="country'+ x +'" multiple="multiple" style="width:300px;">' +
'</select>' +
'etc...');
$("#country" + x).select2({
data: arrayFromPHP
});
Edit Try this:
var newContent = $('' +
'<div>' +
'<select id="country'+ x +'" multiple="multiple" style="width:300px;">' +
'</select>' +
'Remove' +
'</div>' +
'<div><input type="number" name="quantity'+ x +'" min="1" max="10">Remove</div>'
)
$(wrapper).append(newContent);
newContent.find("#country" + x).select2({
data: arrayFromPHP
});
I have been trying to figure out how to get all the input elements inside a div including select and textarea and pass them to editor, so far i figured out with input but i am just stuck with the rest.
Here is the code so far
function InsertShortcode(elem) {
var shortcodeName = elem.parentElement.id;
var inputs = document.getElementById(shortcodeName).getElementsByTagName('input'), i=0, e;
var inputs_val = '[' + shortcodeName;
while(e=inputs[i++]){
if(e.id){
inputs_val += ' ' + e.id + '="' + e.value + '"';
}
}
inputs_val += ']';
window.send_to_editor(inputs_val);
}
By this i am able to grab all the inputs inside a div where submit button is but still i am not sure how to grab textarea or select inputs.
The problem is that i have to make it dynamic. I will have many "shortcodes" and each will be in it's own div where the button is. But each will have it's own inputs which i can't control so i need to grab them all and send values to editor. Here's example of the code.
<div class="output-shortcodes">
<?php foreach( $theme_shortcodes as $key => $name ) { ?>
<div id="<?php echo $key ?>">
<p>
<h2><?php echo $name ?></h2>
</p>
<?php $form = $key . '_form';
if(function_exists($form)) {
$form(); // this is where the input fields are dynamically created on each shortcode.
}
?>
<button class="button-primary" onclick="InsertShortcode(this)">Insert shortcode</button>
</div>
<?php } ?>
</div>
Use jQuery and the :input pseudo selector:
$('.output-shortcodes').find(':input');
That simple.
https://api.jquery.com/input-selector/
Or wrap it in a <form>, then you can use:
document.getElementById("outputForm").elements...
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements
You can target your wrapper element and locate thru .find() all inputs within:
var inputs = $("#" + shortcodeName).find("select, textarea, input");
If you can use jQuery here is a fiddle: https://jsfiddle.net/q33hg0ar/
<div id="form">
<input type="text" name="input1" />
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<textarea name="notes"></textarea>
<button class="button-primary" onclick="InsertShortcode(this)">Insert shortcode</button>
</div>
<script>
$(document).ready(function() {
$('#form').find('input, select, textarea').each(function() {
console.log($(this).attr('name'));
});
});
</script>
And here it is w/o jQuery: https://jsfiddle.net/67pp3ggu/
window.onload = runIt();
function runIt() {
var elements = document.getElementById('form').childNodes;
var inputTypes = ['text', 'select-one', 'textarea'];
for (var i = 0; i < elements.length; i++) {
var elm = elements[i];
if (typeof elm.type !== 'undefined' && inputTypes.indexOf(elm.type)) {
console.log(elm);
console.log(elm.type);
}
}
}
At the end i switched to jQuery code completely and using :input helped me to resolve the problem.
Here is the complete code that i use now.
$('.vivid-framework-submit-shortcode').click(function(event) {
event.preventDefault();
var shortcodeName = $(this).closest('div').attr('id');
var inputs = $('#' + shortcodeName).find(':input');
var inputsVal = '[' + shortcodeName;
inputs.each(function() {
if($(this).attr('id') != 'content') {
inputsVal += ' ' + $(this).attr('id') + '="' + $(this).val() + '"';
console.log(inputsVal);
}
});
inputs.each(function() {
if($(this).attr('id') == 'content' ) {
inputsVal += ']' + $(this).val() + '[/' + shortcodeName;
}
});
inputsVal += ']';
window.send_to_editor(inputsVal);
});
What does it do? So now when i click on a button within shortcode div first using preventDefault to prevent page to scroll to top, next i grab the id of that div using it as shortcode name, and lastly i grab all the inputs and check if one of the inputs have id content because that will decide if shortcode is enclosed or selfclosed and loop through all inputs outputting their id's and values. and at the end return that to the editor.
Some of the terms may be unfamiliar but those who are familiar to WordPress will recognize terms like shortcode...
At the end final output is:
[bartag foo="value" bar="value"]content from textarea[/bartag]
If you downvote my questions or answers please explain why because i always tend to explain or ask as detailed as i can.
I have a input that have type like this:
<input class="emailSend" name="emailSend" type="hidden">
Then I have a multiple select option like this
<div class="controls">
<select id="email" multiple data-rel="chosen" class="input-xlarge" name="email[]">
<?php
foreach ($atasan as $data) {
echo "<option value='" . $data['email'] . "'>" . $data['email'] . "</option>";
}
?>
</select>
</div>
My problem is, I want to fill that hidden input from the option that selected from multiple select option. So let say, the selected option is 'email1', 'email2', 'email3' then would be affected to hidden type like this 'email1, email2, email3'.
I have try this for 3 hour in jquery and I am stuck. My code is like this.
$("#email").change(function() {
var elements = $("#email option:selected").length;
var input = $(".emailSend");
$(".emailSend").html("");
$.each($("#email option:selected"), function(/*index, element*/) {
input.val(input.val() + $(this).html() + ", ");
if (index < elements - 1) {
//code to remove last comma
//any idea ?
}
});
});
So appreciated for the help...
EDIT Here is the fiddle :JSFIDDLE
Updated FIDDLE now that I see what you meant by looking at the fiddle you made.
this is actually all you need to do...
Updated to include spaces between the addresses!
$("#email").on('change', function() {
var thisval = $(this).val() + '';
var myarr = thisval.split(',');
var newval = '';
myarr.forEach(function(i,v) {
newval += i + ' , ';
});
newval = newval.slice(0, newval.length - 3);
$("#emailsend").val(newval);
});
Commented Version (for learning and stuff)
$("#email").on('change', function() {
//the extra space at the end is to typecast to string
var thisval = $(this).val() + '';
//takes string of comma separated values and puts them
//into an array
var myarr = thisval.split(',');
//Initialize a new string variable and loop through
//the array we just created with MDN's forEach()
var newval = '';
myarr.forEach(function(i,v) {
//add to the string through each iteration,
//including comma with spaces
newval += i + ' , ';
});
//use .slice() to trim three characters off the
//end of the final string. (strip final comma)
newval = newval.slice(0, newval.length - 3);
//and last but not least, assign our newly created
//and properly formatted string to our input element.
$("#emailsend").val(newval);
});
I am still trying to work this out. Currently this is the way it looks, It works on JSFiddle but on my for it only clones once and the clone has data in it that when changed, changes the 1st item
I am trying to streamline my very large form to speed up the processes. I have a section that repeats multiple time that I want to reduce to having coded once with a button to add more if needed. The section cannot be cloned as each is separate and specific. Also note that they each need a unique identifier. As I have it not they ar "transectA", "transectB", etc. Below is a small snippet to give you an idea wof what I am working with. Each select actually has 12 options and there are 14 transects.
<div class="transect">
<select name="transectA" id="transectA">
<option value="">Transect A </option>
<option value = "RIGHT/SED-CORE">RIGHT/CORE</option>
<option value = "RIGHT/HOOP">RIGHT/HOOP</option>
<option value = "RIGHT/CHLPHL-1">RIGHT/TEMPLATE</option>
<option value = "RIGHT/NONE">RIGHT/NONE</option>
<option value = "CENTER/SED-CORE">CENTER/CORE</option>
<option value = "CENTER/HOOP">CENTER/HOOP</option>
<option value = "CENTER/CHLPHL-1">CENTER/TEMPLATE</option>
<option value = "CENTER/NONE">CENTER/NONE</option>
<option value = "LEFT/SED-CORE">LEFT/CORE</option>
<option value = "LEFT/HOOP">LEFT/HOOP</option>
<option value = "LEFT/CHLPHL-1">LEFT/TEMPLATE</option>
<option value = "LEFT/NONE">LEFT/NONE</option>
</select> </div>
I have attempted a couple of solutions (hide/show) & clone but neither give me a satisfactory result. All of the attempts I have tried with append seem to produce basically what the show/hide does.
<script>
$(document).ready(function() {
var $transect = $('.transect');
$transect.on('change', 'select', function() {
var $this = $(this),
$parent = $this.parent(),
$transects = $('.transect');
if($transects.length < 14 && !$parent.next('.transect').length) {
var ltr = String.fromCharCode(65 + $transects.length),
label = 'transect' + ltr;
$transect
.clone(true)
.find('select')
.attr('name', 'transect' + ltr)
.attr('id', 'transect' + ltr)
.find('option:eq(0)')
.text('Transect ' + ltr.toUpperCase())
.end()
.end()
.insertAfter($parent);
}
});
})
</script>
As always, your help will be greatly appreciated
Can anyone advise me why all of these solutions work in JSFiddle but not on my form. Even the script above works on the fiddle but only clones once on the form
you could do something like this:
var counter = 0
$('.add-new-button').click(function(){
$('#transectA').append('<option id="input ' + counter +'" value = "RIGHT/SED-CORE">RIGHT/CORE</option>');
counter++;
});
This will add a new option to #transectA. You can use this method to add form fields elsewhere as well. You can use the counter to make sure it has a unique ID or name or whatever. Good luck
You should be able to combine clone and some DOM manipulation to get the desired affect: http://jsfiddle.net/fjJfk/2/
But you'll likely need to make this example match your own markup/situation.
var $transect = $('._25');
$transect.on('change', 'select', function() {
var $this = $(this),
$parent = $this.parent(),
$transects = $('._25');
if($transects.length < 14 && !$parent.next('._25').length) {
var ltr = String.fromCharCode(65 + $transects.length);
$transect
.clone(true)
.find('select')
.attr('name', 'transect' + ltr)
.attr('id', 'transect' + ltr)
.find('option:eq(0)')
.text('Transect ' + ltr)
.end()
.end()
.insertAfter($parent);
}
});
You can use following;
HTML:
<div id="tempSelect" style="display:none">
<select name="transect" data-mini="true" id="transect">
<option value="">Transect_ </option>
<option value = "RIGHT/SED-CORE">RIGHT/CORE</option>
<option value = "RIGHT/HOOP">RIGHT/HOOP</option>
<option value = "RIGHT/CHLPHL-1">RIGHT/TEMPLATE</option>
<option value = "RIGHT/NONE">RIGHT/NONE</option>
</select>
</div
<fieldset>
<div class="_100">
</div>
</fieldset>
<input type="button" name="newSelect" id="newSelect" value="New"/>
JS:
$("#newSelect").on("click", function() {
var lastSelect = $("._100 select").last().attr("name");
if (lastSelect != undefined) {
var temp = lastSelect.split("_");
var id = parseInt(temp[1]) + 1;
} else {
var id = 0;
}
$("#tempSelect select").attr("name", "transect_" + id);
$("#tempSelect select").attr("id", "transect_" + id);
$("#tempSelect select option:first").text("Transect_" + id);
$("._100").append($("#tempSelect").html());
});
Here is working demo: jsfiddle