I have seen several examples of sending individual parameters to a JavaScript function, but not a List.
When I try to pass a list, it comes to function as a big string. This is what I have:
<select id="namespace" name="namespace"
th:responseList="${responseList}"
th:onchange="javascript:print(this.getAttribute('responseList'));">
<option value="">Select Source Namespace</option>
<option th:each="item : ${responseList}"
th:value="${item.namespace}"
th:text="${item.namespace}"></option>
</select>
function print(responseList) {
console.log(responseList);
}
Try this
<script th:inline="javascript">
var list = [[${responseList}]];
console.log(list );
</script>
Hope work for you
Related
enter image description herebelow is the form
<form method="post" style="display: none;" encType="multipart/form-data" class="landLords1" name="addACourse" action="{{URL::to('/addACourse')}}">
{{ csrf_field() }}
<input type="text" placeholder="Course Title" name="title"><br>
<select name="duration" id="duration">
<option value="1 weeks">1 week</option>
<option value="2 weeks">2 weeks</option>
<option value="3 weeks">3 weeks</option>
<option value="4 weeks">4 weeks</option>
<option value="5 weeks">5 weeks</option>
<option value="6 weeks">6 weeks</option>
<option value="7 weeks">7 weeks</option>
<option value="3 months">3 months</option>
<option value="4 months">6 months</option>
<option value="5 months">5 months</option>
<option value="6 months">6 months</option>
<option value="7 months">7 months</option>
<option value="8 months">8 months</option>
<option value="9 months">9 months</option>
<option value="10 months">10 months</option>
<option value="11 month">11 months</option>
<option value="1 year">1 year</option>
</select><br>
<input type="text" placeholder="price" name="price"><br>
<input type="text" placeholder="Course Code e.g(ECN 504)" name="coursecode"><br>
<input type="text" name="author" placeholder="Authors names"><br>
<input type="file" name="picture" placeholder="select picture"><br>
<textarea name="desscription" id="textArea" cols="30" rows="10" placeholder="write a detail descripton of the content of the course you are creating, write a summary of the course. this content will be displayed went users click on the course"></textarea><br>
<button>submit</button><br>
</form>
Below is the javascript code
function addACourse(param){
//event.preventDefault();
console.log(param);
const theToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
//const theForm = document.getElementsByClassName('landLords1')[0];
var formData = new FormData(param);
formData.append('vin', 'value');
var xhttp = new XMLHttpRequest();
xhttp.open('POST', '/addACourse', true);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
return;
const data = JSON.parse(this.responseText);
console.log(data);
// use data here!
}
}
xhttp.setRequestHeader('X-CSRF-TOKEN', theToken);
xhttp.setRequestHeader("X-Requested-With", 'XMLHttpRequest');
xhttp.setRequestHeader("processData", 'false');
xhttp.setRequestHeader('cache', 'false');
//xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send(JSON.stringify(formData));
}
const theForm = document.getElementsByClassName('landLords1')[0];
theForm.addEventListener('submit', function(event){
event.preventDefault();
addACourse(this);
return;
}, false);
This is my laravel controller
<?php
namespace App\Http\Controllers;
use DB;
use Storage;
use Illuminate\Http\Request;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\UploadedFile;
class AddACourseController extends BaseController
{
public function addACourse(Request $request){
$value = $request->input('coursetitle');
return response()->json(array('data' => $value), 200);
}
}
My intension is not to use Jquery to submit the form. I want to submit the form using xmlHttpRequest(). I keep getting null on the server each time I try to submit the form, have tried using both
$theData = $request->input('coursetitile');
$data = $request->coursetitle;
return response()->json(array('data' => $data, 'theData' => $theData),200);
//note coursetitle is one of the imput field.
I keep getting null, please how do i resolve this.
please I do not want any answer that uses JQuery to resolve this.
I want answer in vanila javascript alone.
As far as I can tell from your screenshots and code, you're not actually submitting any data to the server.
Your first screenshot talks about the Request Payload right at the very bottom. It's slightly cut off, but it looks like you are submitting an empty form. This means that your javascript is not finding any form data to send.
Going backwards through this, you are calling addACourse from your eventlistener with an anonymous function (a closure).
theForm.addEventListener('submit', function(event){
event.preventDefault();
addACourse(this);
return;
}, false);
When you are referring to this in a closure, you are referring to the closure itself, and not the caller. Naturally, the closure has no form, therefore you have no form data.
Instead (this is untested), try to pass a reference to the form to your addACourse function. You may need to tweak it a little to get the form data.
theForm.addEventListener('submit', function(event){
event.preventDefault();
addACourse(theForm);
return;
}, false);
Jason, if your answer were the solution, why would this line:
formData.append('vin', 'value');
Located within his AddAClass() function not appear within the Request body sent to the server?
After wasting a lot of time trying hard to get this done on time, I found out eventually that in setting the attributes of the requestHeader, 'contentType' should be used and not 'content-Type', ie.
I changed
xhttp.setRequestHeader('content-Type', 'multipart/form-data');
to
xhttp.setRequestHeader('contentType', 'multipart/form-data');
this entirely solved the issue, the payload was loaded properly with the formData object and laravel was able to access the input fields.
Thanks a lot guys for making attempts to help me out, stackoverflow is a great community.
I'm trying to use interpolation in a template select options like normal
<select class="form-control" id="staff" name="staff">
<option selected disabled>- Select -</option>
#foreach($staff as $aStaff)
<option value="{{$aStaff->id}}">{{$aStaff->initials}}</option>
#endforeach
</select>
The compile error is clear
Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead.
But i'm still unsure of correct usage. Vue documentation simply gives example
<select v-model="selected">
<!-- inline object literal -->
<option v-bind:value="{ number: 123 }">123</option>
</select>
However i'm unsure how to translate this into using the foreach I need above
Something like this is invalid
<option :value="$aStaff->id">{{$aStaff->initials}}</option>
So just not sure how to interpret ?
Edit: tried using v-for, i get no errors but nothing in the select options
<select class="form-control" id="staff" name="staff">
<option selected disabled>- Select -</option>
<div v-for="aStaff in staff">
<option :value="aStaff.id">aStaff.initials</option>
</div>
</select>
I have staff defined in custom component:
<sale v-if="showModal" #sale="calcFees" :staff="{{$staff}}"></sale>
So when i simply do {{staff}} in the component page, it shows the data i expect to see.
Sale.vue component definition:
<script>
export default {
data: function () {
return {
price: null
}
},
props: {
staff: {
type: Array,
required: true
}
},
methods: {
onSale(){
this.$emit('sale', this.price)
}
}
}
</script>
The code is iterating over a div. Instead, iterate the option.
<option v-for="aStaff in staff" :value="aStaff.id">{{aStaff.initials}}</option>
And remove the div of course.
Now I'm working with Laravel 5.
I got value from select option like below:
select name="billing_provider" onChange="changeLanguage(this.value)"> #foreach($tests as $test)
option value="{{ $test->tax_id }},{{ $test->npi }}" name="billing_provider">
{{ $test->test_name }} </option>#endforeach </select>
Here I need to explode the option value and store it into another text field value.
How can I do that?
First, you have made a mistake building your HTML.
<select> has an attribute name which is going to be the key in the global arrays $_GET or $_POST.
However <option> doesn't have attribute name. You should remove that.
If you want to separate the value of billing_provider in your backend (php /w Laravel), do so.
In your method which handles the submission of the form:
$input = Input::get('billing_provider');
$billing_provider = explode(',', $input);
//Now $billing_provider[0] === $test->tax_id
//And $billing_provider[1] === $test->npi
Or if you want to perform this action before form submission and you're using jQuery, then you can do this:
https://jsfiddle.net/17fkpqbe/
JavaScript (/w jQuery):
$(document).ready(function() {
$('select').change(function() {
$('.inputs').html('');
var $explodedVal = $(this).val().split(',');
for(i = 0; i < $explodedVal.length; i++) {
$('.inputs').append('<input value="' + $explodedVal[i]+'">');
}
});
});
HTML:
<select>
<option></option>
<option value="123,555">Some Name 1</option>
<option value="123,444">Some Name 2</option>
<option value="123,333,555">Some Name 3</option>
</select>
<div class="inputs"></div>
I am a newbie of smarty so please pardon my innocence :oops:
I am following a code left by previous programmer and i have this problem on dynamically changing the values of a select box depending on the selected value of another select box.
So here's the situation:
I have drop down named "Section" and another one named "Subsection".
What i need to come up with is that when i choose a Section the Values of the Subsection will change too and only displays the Subsections which is under that section selected.
here's a javascript simulation of the problem:
<html>
<head>
<title>Box changing demo</title>
<script type="text/javascript">
var items = new Array();
items[0] = new Array("Dog", "Cat", "Pig");
items[1] = new Array("Andromeda", "Boötes", "Cepheus");
items[2] = new Array("Mercury", "Venus", "Earth");
items[3] = new Array("BMW", "Audi", "Bugatti");
function changeItems(){;
num=document.changer.section.options[document.changer.section.selectedIndex].value;
document.changer.subsection.options.length = 0;
for(i=0; i<items[num].length; i++){
document.changer.subsection.options[i] = new Option(items[num][i], items[num][i]);
}
}
</script>
</head>
<body>
<form name="changer">
<select name="section" onchange="changeItems();">
<option value="0">Animals</option>
<option value="1">Constelations</option>
<option value="2">Planets</option>
<option value="3">Cars</option>
</select>
<select name="subsection">
<!--<option>tgntgn</option> -->
</select>
</form>
</body>
</html>
This is what i need to do with smarty.
Anybody?
Thank you for your help.
You can't do it in Smarty, because it just cannot be done with HTML only. You have to use Javascript for this. Look at http://www.texotela.co.uk/code/jquery/select/ - it seems easy enough to implement.
Hope This Answers Your Question
<!--JAVASCRIPT-->
<!--CREATE DROPBOX WHEN SEC1 IS SELECTED-->
<script>
var section= document.getElementById("section").value;
if(section == SEC1){
document.getElementById("subSEC").innerHTML='
<select name="subsection" type="text" id="subsection">
<option value=""></option>
<option value="Sub1">Sub1</option>
<option value="Sub2">Sub2</option>
<option value="Sub3">Sub3</option>
</select>"
';
}
</script>
<!--HTML MARKUP-->
<select name="section" type="text" id="section">
<option value=""></option>
<option value="SEC1">SEC1</option>
<option value="SEC2">SEC2</option>
<option value="SEC3">SEC3</option>
</select>
<!--SPACE TO PLACE DROPBOX FROM JAVASCRIPT-->
<span id="subSEC">
</span>
try something like:
{html_options name=section options=$options selected=$index
onchange="changeItems();"}
where $options and $index (index of selected option in select tag) are assigned in php:
<?php
...
$smarty = new Smarty ();
...
$smarty->assign ( 'index', $some_php_val );
$smarty->assign ( 'options', $some_php_array );
...
?>
for more info check:
http://www.smarty.net/docsv2/en/language.function.html.options.tpl
http://www.smarty.net/forums/viewtopic.php?p=53422
Sorry guys, I should have posted the script directly without cleaning it. Please check the updated script, it should now clear things up. Thanks!
Consider the following JavaScript :
var selected = 0;
var options = 0;
$('.newListSelected').each(function() {
selected = $(this).children('.selectedTxt');
selected = selected.text();
/* Everything before this line works completely fine */
options = $(this).prev();
options.find('option[value=' +selected+ ']').attr('selected', 'selected');
}).remove();
And HTML :
<select name="type[]" style="display: none;">
<optgroup>
<option value="none">Select</option>
</optgroup>
<optgroup label="First Group">
<option value="1">One</option>
<option value="2">Two</option>
</optgroup>
<optgroup label="Second Group">
<option value="10">Ten</option>
<option value="20">Twenty</option>
</optgroup>
</select>
<div class="newListSelected">
<div class="selectedTxt">20</div>
<ul class="newList">
<!-- Other stuff here -->
</ul>
</div>
What I'm trying to do actually is adding the selected attribute to the corresponding select option that has the same value as the text in .selectedTxt. In the code above, it should add selected="selected" to <option value="20">Twenty</option>.
However its not performing as expected, I also tried adding alert(option); below prev(); but it didn't output anything useful.
Thanks.
The Javascript works fine, as can be seen here: http://jsfiddle.net/4HsXp/
If you need to be able to select multiple items in a select element, you need to set the multiple and size attribute, like this:
<select multiple="multiple" size="2">
<option>1</option>
<option>2</option>
</select>
See: http://reference.sitepoint.com/html/select
Edit:
Attaching console.log statements to the new code still does not any problem. Running it on jsfiddle gave me the correct output:
jQuery(select)
Original Value: none
New Value: 20
I'm not sure what you are trying to do, but why couldn't you just select all option elements with proper selectors? If you want to select only some options, then you have to add extra selector attrbiutes.
$('select option').each(function() {
$(this).attr('selected', 'selected');
});