Jquery data split php - javascript

I have this array = var1;var2;var3;var4;var5;var6;var6
and I want to split it with jQuery and put it in different textboxes (txt1),(txt2)...etc,
but I can't find the right code.
<script type="text/javascript">
$(document).ready(function() {
$("#cb_motor").change(function() {
$("#cb_motor option:selected").each(function() {
cb_motor = $('#cb_motor').val();
$.post("http://localhost/sag_app/index.php/motor/motor/buscar_id/", {
cb_motor : cb_motor
}, function(data) {
valores = data.split(';');
});
});
})
});
</script>

If txt1, txt2 are inputs ID and is set following DOM order, you could use:
$("[id^=txt]").val(function(i){
return valores[i];
});

Assuming cb_motor is a select with no multiple, the code can be simplified
$(function() {
$("#cb_motor").change(function() {
$.post("http://localhost/sag_app/index.php/motor/motor/buscar_id/", {
cb_motor : $(this).val()
}, function(data) {
var valores = data.split(';');
$('[name="txt_num_serie_motor"]').each(function(i) {
$(this).val(valores[i]);
});
});
});
});
if it IS multiple, then you cannot do Ajax using each for the selected values since you need to wait for each call to return

Related

How do I turn this code from jQuery to Vanilla Javascipt?

I'm creating a webpage(e-commerce) and I'm trying to put a search bar with autocomplete suggestions and this is my original code with jQuery:
<script>
$(document).ready(function(){
$('#products').keyup(function(){
var query = $(this).val(); var query = document.querySelectorAll(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#productlist').fadeIn(); //
$('#productlist').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#products').val($(this).text());
$('#productlist').fadeOut();
});
});
$('#products').keyup(function() {
if($('#products').val() === '') {
$('#productlist').hide();
}
});
</script>
I'm trying not to use any framework so I wanted to turn the code stated above to vanilla javascript and this is the code I currently have right now:
<script>
document.querySelector(document).ready(function(){
document.querySelectorAll(".products").keyup(function()
{
var query = document.querySelectorAll(this).value();
if(query != '')
{
fetch("search.php")
.then((response))=>response.json())
.then(data)=> console.log(data));
});
}
});
element.addEventListener("click", function (){ console.log("clicked");});
document.querySelector(document).addEventListener('click', 'li', function(){
document.querySelector('#products').val(document.querySelector(this).text());
document.querySelector('#productlist').fadeOut();
});
</script>

get value of element of html in another js file

in my index page i sent a request ajax and response is a number.and i set the response to the value of input with hidden type
<input type="hidden" id="Status">
<script src="js/indexPhone.js"></script>
<script>
$(document).ready(function() {
$("#SendPhone").click(function(e) {
var phoneField = $("#PhoneField").val();
var phoneFieldString = "989" + phoneField.substring(0);
$.ajax({
type:'post',
url:'getSMS.php',
data:{'phoneFieldString':phoneFieldString},
success:(function (response) {
$("#Status").val(response);
})
})
});
});
</script>
and my problem is i want to get this value in another javascript page that i included in my index but it alerts empty. this my indexPhone.js:
$("#SendPhone").click(function() {
alert($("#Status").val());
});
Ajax request is asynchronous, so the second click runs before value is set.
Use events:
// index.html
$("#SendPhone").click(function (e) {
// ...
$.ajax({
// ...
success: (function (response) {
$("#Status").val(response);
$("#Status").trigger("gotSMS");
})
});
});
// indexPhone.js
$("#Status").on("gotSMS", function () {
alert($(this).val());
});

how to get $this value in array in javascript

In message variable I am getting the multiple selected, how to store them in array, after this store in database?
<script type="text/javascript">
$(function () {
$('#lstFruits').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#lstFruits option:selected");
// document.write(selected);
//.var array = string.split(",").val(selected);
var message = "";
selected.each(function () {
message += $(this).val();
// here I am getting the selected ids like 2,4,5 and I
// want to submit all ids in the database.
// While, when I am submitting currently only the last
// id is being submitted.
var vale = [$(this).val()];
//document.write(vale);
$('#second').val(vale);
});
alert(message);
});
});
</script>
How to store all selected values in array and then submit in php page by query?
Try to save the values in array & name of the field whose id is second should be like second[]
<script type="text/javascript">
$(function () {
$('#lstFruits').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#lstFruits option:selected");
var message = [];
selected.each(function () {
message.push($(this).val());
});
$('#second').val(message);
alert(message);
});
});
</script>
For example, you can submit this to php by ajax. (With GET or POST query)
Another guide about ajax
Example
$.post('yourphpfile.php', {data: JSON.stringify(message)})
.done(function(data) { console.log('success'); })
.fail(function() { console.log('error');
// in youphpfile.php
$_POST['data'] ? yourFunctionToInsert($_POST['method']) : null;
btw, to insert in array in your js file, you can also do:
message[] = $(this).val(); //in the loop
$(function () {
$('#lstFruits').multiselect({
includeSelectAllOption: true
});
//create array variable
var selectedValues = new Array();
$('#btnSelected').click(function () {
var selected = $("#lstFruits option:selected");
selectedValues.push(selected);
//then by use=ing ajax you can send this array
$.ajax({
type: "POST",
data: {info:selectedValues},
url: "page.php",
success: function(msg){
$('.answer').html(msg);
}
});
});
});
You can make array then by useing .push method can store values in array, after that by ajax you can send over PHP page.

Passing unique values via GET using AJAX

I'm echoing a table where each link has a unique value, which is value='$passthisvalue' as demonstrated in the example below. I'm trying to pass value='$passthisvalue' (maybe value should be called data-type instead?) when clicking each link with no page refresh. The value should be passed to note.php via GET.
php:
echo "<a href='#note' class='note' value='$passthisvalue' title='note'><img src='note.png' alt='note' title='note' border='0'></a>";
javascript:
<script>
$(".note").click(function() {
var elem = $(this);
$.get("note.php?value=$passthisvalue", function() {
refreshthediv();
});
});
</script>
You need to use the PHP script. If you want to use the passed value then use $(this).attr('value').
Try with this:
<script>
$(".note").click(function() {
var elem = $(this);
//var passthisvalue = "<?php echo $passthisvalue;?>";
//OR
passthisvalue = elem.attr('value');
//$.get("note.php?value="+passthisvalue, function() {
// refreshthediv();
//});
//OR
$.get("note.php", { value : passthisvalue }, function() {
refreshthediv();
});
});
</script>
Maybe you should add data-value to your a tag. it might help try the snippet below.
echo "<a href='#note' class='note' data-value='$passthisvalue' title='note'><img src='note.png' alt='note' title='note' border='0'></a>";
<script>
$(".note").click(function() {
var passthisvalue = $(this).data('value');
$.get("note.php", { value : passthisvalue }, function() {
refreshthediv();
});
});
</script>
Link to what you actually want to link to:
<a href='note.php?value=$passthisvalue' class='note' title='note'><img src='note.png' alt='note' title='note' border='0'></a>
And then read the href attribute with JavaScript.
$(".note").click(function(event) {
event.preventDefault()
$.get(this.href, refreshthediv);
});
});

Jquery ajax displays [object Object]

I basically have 2 drop-down lists and 2 labels.
The first drop-down list is the category selection and the second list loads dynamically the items based on the category.
All is good until now.
At the labels I am trying to display the ItemName and the ItemDescription.
ItemName displays fine but when it comes to ItemDescription for some reason it shows [object Object].
I noticed in console that ItemDescription information is posted correctly, can you please help me find the way to display it correctly?
Jquery:
<script type="text/javascript">
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value));
});
$('#ItemsDivId').show();
$('#ItemsID').change(function (results) {
$('#SubmitID').show();
$('#ItemName').text($("#ItemsID option:selected").text());
$('#ItemDescription').text($("#ItemsID option:selected").text(this.ItemDescription));
});
}
});
});
</script>
Json:
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = from s in db.Items
where s.ItemType.ItemTypeName == itemTypeId && s.ItemActive == true
select new { Value = s.ItemName, ItemsID = s.ItemId ,ItemDescription = s.ItemDescription };
return Json(data);
}
$("#ItemsID option:selected").text(this.ItemDescription); changes the text and returns the element as an object. You can save the description of each item as data with jquery data() function. Then use it in change event..
try changing to this.
<script type="text/javascript">
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
options.data('description','');
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value));
options.data('description',this.ItemDescription);
});
$('#ItemsDivId').show();
$('#ItemsID').change(function (results) {
$('#SubmitID').show();
$('#ItemName').text($("#ItemsID option:selected").text());
$('#ItemDescription').text($("#ItemsID option:selected").data('description'));
});
}
});
});
</script>
I did some play around and I found the solution :
<script type="text/javascript">
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
options.data('description', '');
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value).data('ItemDescription', this.ItemDescription));
});
$('#ItemsDivId').show();
$('#ItemsID').change(function (results) {
$('#SubmitID').show();
$('#ItemName').text($("#ItemsID option:selected").text());
$('#ItemDescription').text($("#ItemsID option:selected").data('ItemDescription'));
});
}
});
});
</script>
Also many thanks to Sampath Liyanage for leading me to the right direction :)

Categories