How can I get the value pair of a specific key? - javascript

I'm wanting to get the key value pair for a the specific div, and only the div that I click on. Right now it is logging the values for each div. How can I get only the value for the specific div that I am clicking on? I'm wanting to update during an ajax success, but I'm stumped as to how to update only a certain div. Any ideas as to how I can do this?
$('.wrapper').on('click', '.bet-button', function() {
var self = $(this);
var gameId = self.attr('gameid');
var awayVal = $('#' + gameId + ' input[name=betAmountAway]').val();
var homeVal = $('#' + gameId + ' input[name=betAmountHome]').val();
var awayId = $('#' + gameId + ' .bet-input-away').data('away-id');
var homeId = $('#' + gameId + ' .bet-input-home').data('home-id');
var pointTotals = $('#' + gameId + ' .total-points').val();
console.log(pointTotals);
var value = awayVal || homeVal;
var id, value;
if (awayVal) {
id = awayId;
value = awayVal;
}
if (homeVal) {
id = homeId;
value = homeVal;
}
if (!value) {
alert('please enter a value!')
} else {
$.ajax({
url: "---------" + userId + "/"+ gameId +"/"+ id +"/"+ value +"",
type: "get",
success: function(response) {
// Makes the inputs inputable again.
$('.bet-input-home').prop('disabled', false);
$('.bet-input-away').prop('disabled', false);
function update(){
var currentSelection = $('#team-select').val();
getGames().done(function(results){
$.each(results, function (i, gameData){
$.each(gameData, function(key, game){
var gamesHome = game.home_team_conference;
var gamesAway = game.away_team_conference;
if(gamesHome == currentSelection || gamesAway == currentSelection){
var gameId = game.id;
var pointTotal = game.total_points_bet;
var gameTime = game.game_time_hour;
var gameDate = game.game_time_date;
var homeId = game.home_team.id;
var awayId = game.away_team.id;
var homePoints = game.total_points_bet_on_hometeam;
var awayPoints = game.total_points_bet_on_awayteam;
var totalPoints = homePoints + awayPoints;
// $('#point-total').append(homePoints + awayPoints);
}
});
});
})
}
update();
This updates html code that is generated dynamically (or at least it is supposed to)
$('.wrapper').append('\
<div id="'+ gameId +'" class="main-wrapper col-lg-6 col-md-6 col-sm-12">\
<div class="game-cards">\
<div class="chart-container">\
<canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\
</div>\
<div class="right-info">\
<h4>' + awayTeam + '<br>' + " # " + '<br>' + homeTeam +'</h4>\
<h5 id="time-channel">'+ gameDate +' # ' + gameTime + '<br>' + ' On ' + network +'</h5>\
<div class="total-points-live">\
<h5>Total Points Bet</h5>\
<h5 class="total-points" id="point-total">'+ totalPoints +'</h5>\
<p>'+ awayTeam +'</p>\
<input class="bet-input-away" data-away-id="'+ awayId +'" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\
<p>'+ homeTeam +'</p>\
<input class="bet-input-home" data-home-id="'+ homeId +'" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\
<p class="bet-button" gameid="'+ gameId +'">Click To Place Bet</p>\
</div>\
</div>\
</div>\
');

Related

How to pass an array data from controller to blade file Laravel

I'm trying to pass an array from Controller to Blade
My Controller:
public function socaucuachuong($id){
$socaucuachuong = CauHoi::groupBy('chuong')->select('chuong', CauHoi::raw('count(id) as Total'))->where('idmonthi','=', $id)->get()->toArray();
return view('DeThi::dethi')->with('socaucuachuong', $socaucuachuong);
}
My Blade file:
$('select').select();
function get_units(id) {
var list = $('#dschuong');
list.empty();
var url = "{{ route('dethi.socaucuachuong') }}"+'/'+ id;
var success = function (result) {
if (result.length <= 0) {
var item = '<div class="input-field"><input type="text" disabled value="Môn này hiện chưa có câu hỏi nào"></div>';
list.append(item);
} else {
for (i = 0; i < result.length; i++) {
var item = '<div class="input-field"><label for="unit-' + result[i].chuong + '">Nhập số câu hỏi chương ' + result[i].chuong + ' (có ' + result[i].Total + ' câu) <span class="failed">(*)</span></label><input type="number" max="' + result[i].Total + '" class="unit_input" onchange="set_sum(' + result[i].Total + ')" name="unit-' + result[i].chuong + '" id="unit-' + result[i].chuong + '" required></div>';
list.append(item);
}
}
};
$.get(url, success);
}
My Route file:
Route::post('socaucuachuong', 'DeThiController#socaucuachuong')->name('dethi.socaucuachuong');
You can get array values in blade like this.
<script>
var socaucuachuong = #JSON($socaucuachuong); // this will be array value.
</script>

Outsourcing jQuery request on solr in external javascript

I am trying to outsource my inline javascript into an external one. The inline code looks like this and it works fine.
<script type="text/javascript">
$.getJSON('../servlets/solr/select?q=mods.genre:issue_a&state:published&rows=1&
fl=returnId,id,search_result_link_text,parentLinkText,mods.title&sort=modified
desc&wt=json',
function (data) {
$(data.response.docs).each(function(i, doc){
let ausgabe = "Ausgabe: ";
let titelmain = doc['search_result_link_text'];
let titelall = doc['mods.title'];
for (let i=0, item; item=titelall[i]; i++) {
if (item.indexOf(titelmain)>=0) {
titelall.splice(i,1);
}
}
let titel = titelall.join(' ' + '|' + ' ');
$('#periodicals').append($('<div class="modified"></div>')
.append('<p class="lastmod-p interline text-content">' +
'<span class="fa fa-arrow-right text-info" />' + ' ' +
'<span style="font-weight:bold">' + (doc['parentLinkText']) +
'</span>' + '<br/>' + '<a class="navbar-link" style="font-weight:bold" href="../receive/'+doc['returnId']+'">' + doc['search_result_link_text'] + '</a>' + '<br/>' + titel + '</p>' + '<p/>')
);
});
});
</script>
The external javascript (new.js) looks like this.
It is stored inside the same folder as the html (index.html) invoking it.
$(document).ready(function(){
jQuery.getJSON('http://localhost:8282/mir/servlets/solr/select?q=mods.genre:journal&state:published&rows=2&fl=id,search_result_link_text,mods.title,mods.title.main,sb_amt,sb_ort&sort=modified desc&wt=json',
function (data) {
$(data.response.docs).each(function(i, doc){
let amt = doc['sb_amt'] ? doc['sb_amt'] : ' ';
let ort = doc['sb_ort'] ? doc['sb_ort'] : ' ';
let alletitel = doc['mods.title'];
let titel = alletitel.slice(1);
titel = titel.join(' ' + '|' + ' ');
let meta = [titel,amt,ort];
let text = meta.join(' ' + '|' + ' ');
$('#periodicals').append($('<div class="modified"></div>')
.append('<p class="lastmod-p interline text-content">' +
'<a class="navbar-link" style="font-weight:bold" href="../receive/'+doc['id']+'">' + doc['search_result_link_text'] + '</a>' + '<br/>' + text + '</p>')
);
});
});
alert('New Documents');
});
I added alert to be sure that the external javascript is beeing resolved.
The alert text pops up correctly but there is no data displayed.
In my HTML Code I have this:
<script src="new.js"></script>
<div class="col-md-4">
<h4 class="text-dark font-weight-bold" style="">PERIODICALS</h4>
<div id="periodicals"></div>
<a style="vertical-align:top" href="../servlets/solr/select?q=mods.genre:journal&
state:published&sort=modified desc"></a>
</div>

How to use search box to filter posts from WordPress API?

I have been able to get a list of posts on a php web page (outside of WordPress). How can I use the search box to filter the existing results by blog title(search term).
Here is my search box
<div class="sbox">
<h4>Search blog by title</h4>
<div class="form-group ">
<input type="text" name="search_box" id="search_box" class="form-control" placeholder="Search by title, author or category" >
</div>
</div>
Here is my ajax attempt
$('#search_box').keyup(function(){
var text = $('#search_box').val();
var api_url_search = `http://example.com/wordpress/wp-json/wp/v2/posts?filter[s]=${text}`;
$.ajax({
url:api_url_search,
dataType: 'json',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var title = response[i].title.rendered;
var search_str =
'<li>'+
'<p>' + title + '</p>' +
'</li>'
;
$('#results').append(search_str);
}
}
});
});
It seems to be looping through every letter that is typed and returning all posts for each letter.
I found the answer. The WordPress api won't enable you to filter by title but you can filter by slug. So the user has to type the title with hyphens (e.g my-title)
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms (5 seconds)
//on keyup, start the countdown
$('#search_box').keyup(function(){
clearTimeout(typingTimer);
if ($('#search_box').val()) {
var text = $('#search_box').val();
typingTimer = setTimeout(doneTyping(text), doneTypingInterval)
}
});
//user is "finished typing," do something
function doneTyping (text) {
// var text = text;
var api_url_search = `http://examle.com/wordpress/wp-json/wp/v2/posts?slug=${text}`;
$.ajax({
url:api_url_search,
dataType: 'json',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var date = response[i].date_gmt;
var slug = response[i].slug;
var excerpt = response[i].excerpt.rendered;
var categories = response[i].categories;
var search_str =
'<td>'+
'<div class="card" style="width: 300px;">' +
'<div class="card-divider">' + (i+1) + ' ' + slug + '</div>' +
' <div class="card-section">' +
'<p>' + excerpt + '</p>' +
'<h4>' + date + '</h4>' +
'<h4>' + 'Category:' + categories + '</h4>' +
'<a href="http://example.com/api-posts.php?">'+
'<input type="button" value="read more">' + '</input>' +
' </a>' +
' </div>' +
'</div>'+
'</td>'
;
$('#results').empty().append(search_str); // empty previous results and append new results
}
}
});
};

Cannot read property : style of Null

I am working on a Trello Board using Vanilla Javascript and I am receiving an error on making my Cards . I have used Local and Session Storage to store the cards and lists respectively but I can't figure out why this error persists after I click on the Add Card Board Button
function newTask(x){
card_index= parseInt(localStorage.getItem("card_indices")) ;
//card_index = parseInt(sessionStorage.getItem("card_indices"));
list_index = parseInt(sessionStorage.getItem("index"));
document.getElementById('myTasks').innerHTML +=
'<div id = "list_' + list_index + ' " class="list-item animated zoomIn" > <h2 id = "title_' + list_index +'" onClick = "modifyObj.titleEdit('+ list_index +')" class="list-item__h2">'+x+'</h2><span id = "span_del_' + list_index + '" class ="btn title-delete" onClick ="modifyObj.titleDelete(' + list_index + ')">\u00D7</span><hr>'+
'<input id = "card_del_' + card_index + '" type="text" class="myInput" placeholder="Title...">' +
'<div class="btn add-items " id = "div_add_list_" onClick = "myCard.titleForm(' + list_index + ',' + card_index + ')" >Add List Item</div>'
'</div>'
sessionStorage.setItem("index", parseInt(sessionStorage.getItem("index"))+1);
}
var myCard = {
card:function(index, card_index){
var enteredElement = document.getElementById('card_del_' + card_index).value;
var textNode = document.getElementsByClassName('text_' + card_index);
textNode.innerText = enteredElement;
if (enteredElement === ""){
alert("You must write something ");
}
else{
document.getElementById("text_").style.display = "block";
}
},
titleForm: function(index,card_index){
element = document.getElementById('card_del_' + card_index);
text = '<li style="display:none" class="text_'+ card_index +'"> <span class = "btn items" onClick = "myCard.cardClose()">u00D7</span></li>'
element.insertAdjacentHTML('beforeend', text);
myCard.card(index,card_index);
localStorage.setItem("card_indices", parseInt(localStorage.getItem("card_indices"))+1);
// card_index+=1;
}};

Problems with Jquery .on()

I'm attempting to use .on() to add a text field when a dynamically created button is clicked. However, for whatever reason, I can't seem to get it working. Anyone see what's wrong? Thanks for any help and sorry if it's something obvious (I'm afraid that it might be but I just can't see it).
$('#the-basics input.typeahead').keyup(function() {
var prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
<div id="the-basics">
<input class="typeahead">
</div>
<div class="new_person new_fields">
</div>
</div>
Changes I made
► Declared variable prs as a global variable
► Remove # from the New Person button's id.
Working Demo
var prs = '';
$('#the-basics input.typeahead').keyup(function() {
prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
<div id="the-basics">
<input class="typeahead">
</div>
<div class="new_person new_fields">
</div>
</div>
Remove # from the New Person button's id.
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
Declare prs outside the click event like following.
var prs;
$('#the-basics input.typeahead').keyup(function () {
prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
var prs = $(this).val().split(' ');
is not a global variable, and inaccessible inside $('div#example').on('click', '#addpersonbutton', function() { so duplicate it inside your second function
EDIT: to make it clear:
$('#the-basics input.typeahead').keyup(function() {
var prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var prs = $(this).val().split(' ');
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});

Categories