jQuery Split dropdown value - javascript

Help needed to split the dropdown value and put them to the inputs in two different tables.
$(document).on('change', '[id^="SelID_"]', function () {
SplitSelectValue($(this));
});
function SplitSelectValue(obj) {
var data = obj.find("option:selected").val();
var arr = data.split('|');
var tr = obj.closest('tr');
tr.find("[id^='SelVala_']").val(arr[0]);
tr.find("[id^='SelValb_']").val(arr[1]);
tr.find("[id^='SelValc_']").val(arr[2]);
tr.find("[id^='SelVald_']").val(arr[3]);
tr.find("[id^='SelVale_']").val(arr[4]);
}
jsfiddle

Modify your function like this:
function SplitSelectValue(obj) {
var data = obj.val();
var arr = data.split('|');
var tr = obj.closest('tr');
tr.find(".SelVala_").val(arr[0]);
tr.find(".SelValb_").val(arr[1]);
tr.find(".SelValc_").val(arr[2]);
var table2 = $('#AddFieldsToDebugDiv');
var row = table2.find('tr:eq(' + tr.index() + ')');
row.find(".SelVald_").val(arr[3]);
row.find(".SelVale_").val(arr[4]);
}
Values SelVald_ and SelVale_ go to corresponding row of the second table. Also I changed ids to classes because id cannot be duplicated.
Demo: http://jsfiddle.net/BE5Lr/3745/

Try replacing tr.find with $
function SplitSelectValue(obj) {
var data = obj.find("option:selected").val();
var arr = data.split('|');
//var tr = obj.closest('tr');
$("[id^='SelVala_']").val(arr[0]);
$("[id^='SelValb_']").val(arr[1]);
$("[id^='SelValc_']").val(arr[2]);
$("[id^='SelVald_']").val(arr[3]);
$("[id^='SelVale_']").val(arr[4]);
}
Gave me the expected results

Related

Jquery check if data exist as a substring on an html table

Check if data exist on an html table even if it is a substring.
var substring = 'find me'; //substring or data that you wanted to check
var dataExist = [];
$('table#tableID tr').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
if($(this).text().indexOf(substring) == -1)
dataExist.push(true);
}
});
console.log(dataExist.includes(true))
If you're just trying to figure out if a table has a string anywhere in it, you could simply use indexOf() on myTable.innerText.
var myTable = document.getElementById('myTable');
var exists = myTable.innerHTML.indexOf('find me');
If you want to make sure the exists variable is always a boolean, you can use the below line.
var exists = !! ~ document.getElementById('tableID').innerHTML.indexOf('find me');

Working with Localstorage for put content in table (JQuery)

I have a big problem working with this.
I have a table in my html, in my js I'm using localstore (I have never used that before)
I insert a new row, and it is stored with localstore, I create a JSON.
For putting the ID of the raw, I just get the length of my localstorage.
For example, I have 3 rows, with IDs 1, 2 and 3.
If I decide to delete one, we can say the number 2, I can delete it, yeah, but the next time when I create a new raw I'll have the id = 2.
why?, because I use localstorage.length+1 for putting the id, so... If I had 3 before, the next time I'll get a 3, I'll replace my content where ID = 3.
what can I do for avoid that mistake?
my JS is this
crearTabla(tablastorage)
$("#btnNuevo").on('click',function(){
$("#mymodal1").modal("show");
$('#btnGuardar').data('evento','crear');
});
$("#btnCargar").on('click',function(){
crearTabla(tablastorage)
});
$("#btnGuardar").on('click',function(){
if($(this).data('evento') == "crear"){
Crear();
$('input:text').val('');
}
else{
Modificar();
}
$("#mymodal1").modal("hide");
});
function crearTabla(data){
$("#tabla").empty();
$.each(data, function(index, val){
var temp = JSON.parse(val);
var $tr = $("<tr/>");
var $tdID = crearTD(temp.id);
var $tdMatricula = crearTD(temp.matricula);
var $tdNombre = crearTD(temp.nombre);
var $tdSexo = crearTD(temp.sexo);
var $tdAccion = crearAccion(temp);
$tr.append($tdID, $tdMatricula, $tdNombre, $tdSexo, $tdAccion);
$("#tabla").append($tr);
$('input:text').val('');
})
}
function Crear(){
var $tr = $("<tr/>");
var $tdID = crearTD(tablastorage.length+1);
var $tdMatricula = crearTD($("#matricula").val());
var $tdNombre = crearTD($("#nombre").val());
var $tdSexo = crearTD($("#sexo").val());
var JSon = {
id:tablastorage.length+1,
matricula:$("#matricula").val(),
nombre:$("#nombre").val(),
sexo:$("#sexo ").val()
}
if($('#matricula').val()=='' || $('#nombre').val()=='' || $('#sexo').val()==''){
alert("Uno o mas campos vacios");
}
else{
tablastorage.setItem(tablastorage.length, JSON.stringify(JSon))
var $tdAccion = crearAccion(JSon);
crearTabla(tablastorage)
$('input:text').val('');
}
};
function crearTD(texto){
return $("<td/>").text(texto);
};
function crearAccion(objeto){
var $td = $("<td/>");
var $div = $("<div/>",{
class:'btn-group',
role:'group'
});
var $btnElminar = $("<button/>",{
class:'btn btn-danger eliminar'
}).html("<i class='glyphicon glyphicon-remove'></i>"
).data('elemento',objeto);
var $btnModificar = $("<button/>",{
class:'btn btn-info modificar'
}).html("<i class='glyphicon glyphicon-pencil'></i>"
).data('elemento',objeto);
$div.append($btnElminar, $btnModificar)
return $td.append($div);
};
$("#tabla").on('click','.eliminar',function(event){
console.log($(this).data('elemento').id)
tablastorage.removeItem($(this).data('elemento').id-1)
crearTabla(tablastorage)
});
$("#tabla").on('click','.modificar',function(event){
index = $(this).data('elemento').id-1;
var $elemento = $(this).data('elemento');
$('#btnGuardar').data('evento','modificar');
$('#id').val($elemento.id);
$('#matricula').val($elemento.matricula);
$('#nombre').val($elemento.nombre);
$('#sexo').val($elemento.sexo);
$("#mymodal1").modal("show");
});
and my html have this code:
http://notes.io/wAYL
Two extra things.
1. Sorry for my bad english, If I've made a mistake is because I speak spanish, not english all the time, I need to improve my skills with the languague.
2. Also because I don't know how to put the code here. I just tried and I faild so many times.
<-- Please don't erase this -->
What i usually do is store whole arrays in one storage key as JSON.
When you load page you get whole array using something like:
var data = JSON.parse( localStorage.getItem('tableData') || "[]");
$.each(data, function(_, item){
// append html to table for each item
});
Then in your Crear() you would push the new item into the array, and store the whole array
var JSon = {
id: +new Date(),
matricula:$("#matricula").val(),
nombre:$("#nombre").val(),
sexo:$("#sexo ").val()
}
data.push(JSon);
localStorage.setItem('tableData', JSON.stringify(data));
Similar to remove an item , splice() the array to remove it from main array and store again.
One suggestion for ID is use current timestamp

Jquery insert function params into selector

I have a Jquery function that helps with validation over 1 object. I need to expand it so that the function will run over 3 different objects. I am trying to define a function that takes a parameter(whichquote) to insert the appropriate object in the function. Here is my code. What I am doing wrong? I assume I do not have the selector correct as the code works if I put it in.
Original Function that works:
var depends = function() {
var selectorD = $("input[name^='lead[quote_diamonds_attributes]'], select[name^='lead[quote_diamonds_attributes]']");
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
Function I am trying to create that allows me to use it on other objects. This currently does not work.
var depends = function(whichquote) {
var selectorD = $("input[name^='lead[+ whichquote +]'], select[name^='lead[+ whichquote +]']");**
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
I think the problem is with my concating in the var selectorD but cannot seem to get the syntax correct.
Your selector isn't actually inputting whichquote because the string concatenation is incorrect.
Try
var selectorD = $("input[name^='lead[" + whichquote + "]'], select[name^='lead[" + whichquote +"]']");

How do I retrieve the first value from an array?

I have a call to a YouTube XML sheet that works perfectly fine. However, I am having trouble setting a value from one of the arrays. I want the first value from "songID" to be set as "first". I've tried doing this:
var first = songID[0]
but it only makes a new array with only the first character of each value... Any suggestions?
$(window).load(function(){
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/F9183F81E7808428?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
$.each(data.feed.entry, function(i, item) {
var songID = item.media$group.media$content[0].url.substring(25, [36]);
var songTitle = item.title.$t;
var descript = item.media$group.media$description.$t;
var songAth = descript.slice(3);
}
}
})
You are already in an each() loop, so you shouldn't try to access it as an array, but just as a value. Just try:
if(i == 0){
var first = songID;
}
Are you sure what you're getting is actually an array? What makes you think that? Because if you ask for aString[0], you'll still get the first character back, because you can access string characters as if they're array elements. If it is indeed an array, just use var myString = myArray.join(""); and it'll become a string.
$(document).ready(function() {
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/9002A5F66694EBA0?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
$.each(data.feed.entry, function(i, item) {
var songID = item.media$group.media$content[0].url.substring(25, [36]);
var songTitle = item.title.$t;
var descript = item.media$group.media$description.$t;
var songAth = descript.slice(3);
if(i==0){
alert("firstId is "+songID );
}
});
});
});
or just for first id:
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/9002A5F66694EBA0?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
console.log(data.feed.entry[0].media$group.media$content[0].url.substring(25, [36]));
});
});

Get value from dynamically created checkboxes if checked

I made few checkboxes along with a button which on submit calls a function where I want to get all the values of checkboxes which have been checked.
Code for creating those checkboxes is:
for (var loop=0; loop < count; loop++)
{
var chap = document.createElement("input");
chap.type = "checkbox";
chap.value = nearby[loop];
chap.id = nearby[loop];
document.getElementById("mapdisplay").appendChild(chap);
var nearo = nearby[loop];
var s = document.getElementById("mapdisplay");
var text = document.createTextNode(nearby[loop]);
s.appendChild(text);
var br = document.createElement('br');
s.appendChild(br);
}
Now I want to retrieve the values which are checked. I am trying this (but to no available)
function fsearch()
{
var p = x;
var narr = new Array();
narr=nearby;//a global arr
var checked_vals = new Array();
$('#mapdisplay input:checkbox:checked').foreach()
{
checked_vals.push(this.value);
}
Please suggest something to retrieve the checked values id of generated values are in array form. I can not use $("#nearby[0]").val().
var checkedCheckBoxesValueArray = $('#mapdisplay input:checkbox:checked').map(
function(){
return this.value;
}).get();
Correct syntax would be:
$('#mapdisplay input:checkbox:checked').each(function(index) {
checked_vals.push($(this).val());
});
Live test case: http://jsfiddle.net/e6Sr3/

Categories