How to get ID value using map() - javascript

I've page that contain the list button and search button.
index.php :
<li class="page-item" id="'.$i.','.$record_per_page.'"><a class="page-link" href="javascript:void(0);" >'.$i.'</a></li>
<input class="form-control" type="text" placeholder="insert your keyword ..." aria-label="Search" id="budget_keyword" name="<?=$record_per_page;?>">
script.js :
$(document).on('click','#table-content .page-item',function () {
var mode = this.id.split(',');
var page = mode[0];
var p = mode[1];
var keyword = $('#budget_keyword').map(function() {
return this.id.value;
});
$.ajax({
url: "paging.php",
method: "POST",
data: { page: page, p: p, keyword: keyword },
success: function (data) {
$('#table-content').html(data);
}
})
});
My Goals are :
When user click the li button, then it will pass 2 variables which containing values from #page-item and #budget_keyword id
I already got the value of #page-item from my script above, but for the #budget_keyword, it seems returning an object which i cannot understand below :
Object { length: 0, prevObject: Object(1) }
I just need the value from user input text inside searchbox (#budget_keyword)
Can someone give me an idea ?
sorry for my bad english

Seems like multiple inputs with same id="budget_keyword" exist in your HTML.Due to that keyword is not coming properly (or in other words to say map() not working).
You can use .next() to get desired keyword. Check below code:
$(document).on('click','#table-content .page-item',function () {
var mode = this.id.split(',');
var page = mode[0];
var p = mode[1];
var keyword = $(this).next('.form-control').val();
$.ajax({
url: "paging.php",
method: "POST",
data: { page: page, p: p, keyword: keyword },
success: function (data) {
$('#table-content').html(data);
}
})
});
Note:- if only one id="budget_keyword" exist in whole document,then directly do:
var keyword = $('#budget_keyword').val();

Related

How can i assing a different class after a success ajax response

I'm working in a net core app, i made a HttpPost function to know if an user marked like.
This is the function code:
var likesCancion = (from likesCanc in _context.table
where likesCanc.SongId == idCancion && likesCanc.UserId == idUser
select likesCanc.Likes).FirstOrDefault();
if (likesCancion == 1)
{
return 1;
}
else
{
return 0;
}
I have this:
<div class="col-3 col-sm-2 col-md-2">
<i class="far fa-heart" id="heart" data-idAudio = #song.Id>
<span class="badge" >#song.Likes</span>
</i>
</div>
This is the <div> that I want to change at the start of the page if the user liked it or not.
The #song.Likes its data filled from the database.
I made an ajax request inside a for loop and get the respond of my HttpPost function:
const iconosCorazon = document.querySelectorAll('#heart');
setTimeout(function () {
let idUser = $('#inputidUsuario').val();
function makeRequest(i)
{
$.ajax({
type: "POST",
url: "checkHeart",
data: { idCancion: i, idUser: idUser },
dataType: "text",
success: function (msg) {
console.log(msg);
**if (msg == 1) {
$('.fa-heart').removeClass("far text-dark");
$('.fa-heart').addClass("fa text-danger");
}
else
{
$('.fa-heart').removeClass("fa text-danger");
$('.fa-heart').addClass("far fa-heart");
}**
},
error: function (req, status, error) {
console.log(msg);
}
});
}
for (var i=0;i<iconosCorazon.length;i++) {
let idCancion = iconosCorazon[i].getAttribute('data-idAudio');
makeRequest(idCancion);
}
I want to assign the css class to the correct element coming from the function result.
The issue here its that ajax execute all the elements at once and change the classes only with the last lopped element. So the question is how can i assign the rigth class to each div element. eg: If result == 1 paint red, if result == 0 paint other color.
Sorry for my bad english
Im trying to make this code works
You should use $(".fa-heart:eq(index)") to locate the each element with same class name. Sample code below:
$(".div_test:eq(0)").css("border","2px solid yellow");
Test Result:

Refresh attribute value after html() with ajax

I am making start/pause button that works like this:
var btns = document.querySelectorAll(".repairToggle");
for (i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", manageOrderStatus);
}
function manageOrderStatus() {
var func = this.getAttribute("func");
var btn = this;
var endpoint = "{% url 'mtn:ajax_repair_toggle' %}";
$.ajax({
url: endpoint,
type: "GET",
data: {
'func': func,
},
success: function (data) {
$(btn).html(data);
}
});
}
I have start and stop buttons stored in separate html files:
work_order_start.html:
<div type="button" class="repairToggle" func="start">
<svg>...</svg>
</div>
work_order_pause.html:
<div type="button" class="repairToggle" func="stop">
<svg>...</svg>
</div>
In view i render one of the buttons based on the value of func attribute:
def repair_toggle(request):
...
func = request.GET.get('func')
if func == 'stop':
return render(request, 'mtn/work_order_start.html')
else:
return render(request, 'mtn/work_order_pause.html')
The problem is it only works once. After the first click it keeps executing ajax call but it sends the same old func value in request. How do i fix that?
UPDATE:
I figured out the problem. $(btn).html(data); only replaces the svg element. So the func stays the same. If i do this instead:
<div type="button" class="repairToggle">
<svg id='funcButton' func="stop">
</div>
How do i get func out of svg. I tried this.getElementById('funcButton').getAttribute("func"); but it doesn't work.
You are inserting the button inside the original button.
Change work_order_pause.html and work_order_start.html to only contain the svg and add in success function :
if(func == "start"){
this.setAttribute("func", "stop")
}
else{
this.setAttribute("func", "start")
}

Javascript, parsing multiple values in a variable

I have a working html form (in laravel) that is using a javascript call to employe Ajax.
Right now I'm using console log to make sure my click event shows the variables which it does.
However, because of how my values are below, I get multiple values in one variable and I'm wondering if there's a way to parse them into their own.
For example, in my form I have multiple values sharing table cells:
<form id="saveLineup">
#foreach($lists as $list)
<tr style="text-align:center;">
<td id="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td id="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td id="category">{{$list['CATEGORY']}}</td>
<td><input id="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
</form>
But when I log my variables I get
category: "categoryOne" //which is correct
detailColor: "123/Blue - Description"
productNumber: 123 - productOne
What I'd like to do is parse those and have it all as separate values like so:
category:"categoryOne"
detail: "123"
color: "Blue"
productNumber: "123"
productDescription: "productOne"
Is there a way to do that within my JS?
$("#addToLineup").click(function (e) {
var productNumber = document.getElementById("productNumber").innerHTML = productNumber;
var detailColor = document.getElementById("detailColor").innerHTML = detailColor;
var category = document.getElementById("category").innerHTML = category;
updatedata.productNumber = productNumber;
updatedata.detailColor = detailColor;
updatedata.category = category;
$.ajax({
url: "/test/addToLineup",
data: updatedata,
_token: phpVariables.csrfToken,
type: "POST",
beforeSend: function () {
showLoading(element);
},
success: function (data) {
location.reload();
},
});
});
I believe the simplest way is splitting your variables like this:
var detailColor = "123/Blue - Description";
var productNumber = "123 - productOne";
var first = detailColor.split(' - ');
var just_color = first[0].split('\/');
var detail = just_color[0];
var color = just_color[1];
var second = productNumber.split(' - ');
var product_number = second[0];
var product_description = second[1];
console.log(detail , color, product_number, product_description);

Stop .blur() function from triggering on select statement but remain on span

I am trying to create an inline edit function to trigger differently on different elements.
I have tried to use other plugins but haven't been able to get them to do exactly what I want so have decided to try to create a plugin of my own, while learning jquery along the way.
The issue I am currently having is that I have a .blur event that is triggering on a span element correctly and this is what I want but when the element is a select element I don't want the blur event to trigger. As the code is below the blur event triggers and it is not the desired result. Can anybody advise how I can only trigger the blur() event on span elements and nothing else
$('.inlineEdit-jmc').inlineEditJmc({
fieldsArray: {
table-column1: 'field-table-column1',
table-column2: 'field-table-column2'
}
});
(function ( $ ) {
$.fn.inlineEditJmc = function(options) {
//Set Default Settings
console.log(options);
var settings = $.extend({
'pk': null,
'table': null,
'field': null,
'url': null,
'type': null,
'fieldsArray': null
},options)
if(settings.fieldsArray == null){}else{
var fields = new Array();
}
function load_settings(this_selected){
settings['pk'] = this_selected.attr("data-pk"); // pk of table to be updated
settings['table'] = this_selected.attr("data-table"); // table name of table to be updated
settings['field'] = this_selected.attr("data-field"); // name of the field in the table being updated
settings['url'] = this_selected.attr("data-url"); // url for the ajax call to be sent to.
settings['type'] = this_selected.attr("data-type"); // type of input being used. Input or Select
settings['value'] = this_selected.text(); //
settings['class'] = this_selected.attr("class"); // The Class
console.log(settings['table'] +' '+ settings['value']+ ' '+ settings['class']);
// if there are optionional inserts passed lets grab them
console.log('passed options:');
if(settings.fieldsArray == null){}else{
//var fields = [];
$.each(settings.fieldsArray,function(k,v){
//console.log('settings['+k+'] '+this_selected.attr(v));
$obj={};
$obj[k] = this_selected.attr(v);
fields.push($obj);
});
}
}
$(this).on('mouseover', function(event) {
$(this).addClass("ui-state-hover");
}).on('mouseout', function(event) {
$(this).removeClass("ui-state-hover");;
});
if($(this).is('select')){
$(this).on('change', function(){
alert('changed');
alert($(this).val());
//console.log($(this));
//load_settings($(this));
var nt = $(this).text();
var jsonstring = JSON.stringify(fields);
// AJAX
});
}
if($(this).is('span')){
$(this).on("blur", function () {
alert('span');
load_settings($(this));
var nt = settings['value']
console.log('comment: '+settings['value']);
// we are going to update the db here.
console.log('Insert');
console.log(fields);
var jsonstring = JSON.stringify(fields);
console.log(jsonstring);
$.ajax({
type: 'POST',
url: settings['url'],
data: {
fieldsArray: fields,
pk: settings['pk'],
table: settings['table'],
field: settings['field'],
value: settings['value']
},
cache: false,
success: function(data,status){
console.log(data);
}
});
});
}
}
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class=''>
<select class='inlineEdit-jmc' ><option value='0' data-pk='3' data-url='/path/to/js/ajax/ajax.php' data-table='mysqltablename' data-field='ignore'>NO</option>
<option value='1' data-pk='3' data-url='/path/to/js/ajax/ajax.php' data-table='mysqltablename' data-field='ignore' selected>YES</option>
</select></td>
<td class=''><span class='inlineEdit-jmc' id='input' data-pk='3' data-url='/path/to/js/ajax/ajax.php' data-table='mysqltablename' data-field='comment' contenteditable='true'>Text that can be edited</td>
Try this code section in place of yours that begins if($(this).is('span')){
$(this).on("blur", function ()
$("span").on("blur", function () {
// your function content here
});
$("span select").on("blur", function () {
e.stopPropagation();
});
The two alternative selectors act like a case statement in jQuery

How to set search results to pre-selected in select2?

Alright, so I'm trying to use select2's tagging and AJAX functionality in conjunction for my categories selection.
Currently, the user can search for categories to add to their post. One nice thing I noticed is that, select2 won't let you select the same selection twice (it's grayed and nothing happens when you click on it).
Here's my challenge... let's say a user is editing a post and already has categories selected. These categories appear below the select2 search. For example, let's say the user has the category "Life" selected. This will appear below already checked off.
The problem arises though, when the user searches for "Life". They'll be able to select it and add it again. I could just parse the previous selections and negate the selection, but I'd really like to use the built in functionality of select2 for the sake of consistency.
So how do I set incoming AJAX results to be already selected so that they can't be selected again?
Here's a fiddle. Notice how "Experiences" is grayed out when you search for it, but "life" is not even though it's already selected.
http://jsfiddle.net/odLnznct/1/
function formatStuff(stuff) {
if (stuff.loading) return 'Searching...';
markup = "<p>" + stuff.text + "</p>";
return markup;
}
function formatRepoSelection(stuff) {
return stuff.cat_name || $('.js-select').val();
}
function catAdd() {
var addCat = div = clo = label = labelText = null;
cat = $('.js-select').select2('data');
addCat = cat[0].text;
div = $('#categories-cat_name div.checkbox:first');
clo = div.clone();
$('input[type="checkbox"]', clo).val(addCat);
label = $('label', clo);
labelText = label[0].childNodes[label[0].childNodes.length - 1];
labelText.textContent = addCat;
$(div).before(clo);
}
$('.js-select').select2({
tags: true,
ajax: {
url: 'https://api.myjson.com/bins/58uwe',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data, page) {
var select2Data = $.map(data, function (obj) {
obj.id = obj.cat_id;
obj.text = obj.cat_name;
return obj;
});
return {
results: select2Data
};
},
cache: true
},
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 1,
templateResult: formatStuff,
templateSelection: formatRepoSelection
});
$('.js-select').on('select2:select', function () {
catAdd();
});
You can try this.
Since your results could be multiple, you need to set your select element's multiple true to enable it and just add selected option as default value.
You can do it either javascript or html.
<div id='select-test'>
<select class="js-select" style="width:90%;" multiple=true>
<option value="Life" selected=true>Life</option>
<option value="Joy" selected=true>Joy</option>
</select>
</div>

Categories