$('.remove-member').click(function () {
var toRemove = $(this).parent().text().slice(0, -1);
var members = $(this).parent().siblings('input[name=group-members]').val().split(' ');
$(this).parent().remove();
removeElement(members, toRemove);
members = members.join(' ');
$(this).parent().siblings('input[name=group-members]').val(members);
});
In the above, everything works until the last line (setting the value to the string contained in members). Displaying the variable members in the console displays the expected string, signifying that $(this).parent().siblings('input[name=group-members]') is traversing the DOM correctly. My HTML is below:
<form method='POST' action='action.php'>
<input type='text' value='[ GROUP NAME GOES HERE ]' name='group_name' />
<input type='text' name='add-member' />
<div class='group_member'>name01<span class='remove-member'>x</span>
</div>
<div class='group_member'>name02<span class='remove-member'>x</span>
</div>
<div class='group_member'>name03<span class='remove-member'>x</span>
</div>
<div class='group_member'>name04<span class='remove-member'>x</span>
</div>
<input type='text' value='name01 name02 name03 name04' name='group-members' />
<input type='Submit' value='Update' />
</form>
Directly referencing $('input[name=group-members]') is not an option due to the nature of the page.
removeElement function:
function removeElement(arr) {
var what, a = arguments,
L = a.length,
ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax = arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
$('.remove-member').click(function () {
var toRemove = $(this).parent().text().slice(0, -1);
var members = $(this).parent().siblings('input[name=group-members]').val().split(' ');
$(this).parent().remove();
removeElement(members, toRemove);
members = members.join(' ');
$(this).parent().siblings('input[name=group-members]').val(members);
});
You are removing the parent..
$(this).parent().remove();
So the call..
$(this).parent().siblings('input[name=group-members]').val(members);
Shouldn't work anymore because you just killed the containing DOM node.
Related
I would need help to move forward with my code. I want each time the user writes (,) between two words, they should be separated and form two li elements in a list. Right now the whole code works but I would get tips on how to make a comma separated text.
var names = [];
function convert_to_list()
{
var theName = document.getElementById("enter").value;
if (theName == "" || theName.length == 0)
{
return false; //stop the function since the value is empty.
}
names.push(theName);
document.getElementById("converted_list").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
}
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<input onclick="convert_to_list()"value="Konvertera" type="button"/>
<div id="converted_list"><ul></ul></div>
</form>
</fieldset>
You could do something like I did in this codepen.
Use the split function to split a string when it encounters a specified character, in your case a comma.
The HTML (pug) would look like this:
form
label
span seperated list
input#js-seperatedList(type="text")
ul.results
And this will be your JavaScript code:
const inputValue = document.querySelector('#js-seperatedList')
const results = document.querySelector('.results');
inputValue.addEventListener('keyup', (e) => {
results.innerHTML = ''
const res = e.target.value.split(",")
for (let i = 0; i < res.length; i += 1) {
const e = document.createElement('li');
e.innerHTML = res[i]
results.appendChild(e)
}
})
Use split() function to separate the words using comma and then create li element and append into final ul element.
const btnEnter = document.getElementById("btnEnter");
btnEnter.addEventListener("click", convert_to_list);
const ulElements = document.getElementById("converted_list").children[0];
function convert_to_list() {
const theName = document.getElementById("enter").value;
if (theName.length <= 0) {
return false;
}
const list = theName.split(",");
const liElements = [];
for (const value of list) {
const li = document.createElement('li');
li.innerHTML = value.trim();
ulElements.appendChild(li);
}
}
<html>
<head></head>
<body>
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<input id="btnEnter" value="Konvertera" type="button"/>
<div id="converted_list"><ul></ul></div>
</fieldset>
</form>
</body>
</html>
i would recommend using addEventListener which is much simpler than calling functions inside html elements , and to do what you asking the split() method can do that with any string , if there is something you don't understand with this code i am happy to help
document.querySelector('.btnclick').addEventListener('click', function () {
const theName = document.getElementById('enter').value;
if (theName.includes(',')) {
theName.split(',').map(function (e) {
if (e !== '')
return document
.querySelector('#converted_list')
.insertAdjacentHTML('afterbegin', `<li>${e}</li>`);
});
} else if (theName !== '' || theName.length !== 0) {
document
.querySelector('#converted_list')
.insertAdjacentHTML('afterbegin', `<li>${theName}</li>`);
}
});
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<input class="btnclick" value="Konvertera" type="button" />
<div id="converted_list">
<ul></ul>
</div>
</form>
document.querySelector("form").onclick=(ev,v)=>{
if (ev.target.tagName==="BUTTON") {
ev.preventDefault();
v=ev.target.previousElementSibling.value.trim();
ev.target.nextElementSibling.innerHTML=(v>""?"<li>"+v.replaceAll(",","</li><li>")+"</li>":"");
}
}
<html>
<head></head>
<body>
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<button>Konvertera</button>
<div id="converted_list"><ul></ul></div>
</fieldset>
</form>
</body>
</html>
I'm trying to compare a input value with two paragrapah to check if the input value exists in both paragraph. So, I did this below. But the code is not working well :/. Could someone explain how to do it?
<input type="text" class="input-text" name="billing_district" id="billing_district" placeholder="" value="">
<p class="regions">Dias Macedo, Itaperi, Passaré, Taquara, Serrinha</p>
<p class="regions">Dias Macedo, Dendê, Edson Queiroz, Taquara</p>
<p class="regions">Jereissati, Dendê, Forquilha, Centro, Taquara</p>
jQuery(function ($) {
var a = $('#billing_district').val().normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().split();
var b = $('.regions').text().normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().split(", ");
var index = $.grep(b, function (element, index) {
if ($.inArray(element, a) != -1) {
console.log(element);
}
});
});
This works, though you did not specify that the code should look at whole terms between commas. This code outputs true even if two letters occur in all the p's.
But you could add an extra loop to check the splitted strings.
jQuery(function($) {
const $input = $('#billing_district');
const b = $('.regions');
$('#billing_district').on('keyup', function(){
let a = $input.val();
let count = 0
$.each(b, function(i, p) {
console.log($(p).text().replace(/\s/g, ""),a);
if ($(p).text().replace(/\s/g, "").includes(a)) {
count++;
}
});
let valueIsInAllParagraphs = (count == 3);
console.log(valueIsInAllParagraphs);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input-text" name="billing_district" id="billing_district" placeholder="" value="">
<p class="regions">Dias Macedo, Itaperi, Passaré, Taquara, Serrinha</p>
<p class="regions">Dias Macedo, Dendê, Edson Queiroz, Taquara</p>
<p class="regions">Jereissati, Dendê, Forquilha, Centro, Taquara</p>
I have a javascript OnChange function on a column having textboxes which captures the name of each row in a column. I am appending all the names and storing in variable.
Now , suppose user clicks same textbox again , I don't want to append that name again.
var AppendedString = null;
function onChangeTest(textbox) {
AppendedString = AppendedString;
AppendedString = AppendedString + ';' + textbox.name;
// this gives null;txt_2_4;txt_2_6;txt_3_4;txt_2_4 and so on..and I don't want to append same name again , here it's txt_2_4
}
My Input text :
<input type="text" name="txt_<%=l_profileid %>_<%=l_processstepsequence%>" value="<%= l_comments%>" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;">
Those rows seem to have unique names.
you can simply check if AppendedString already contains that name :
var AppendedString=''
function onChangeTest(textbox) {
if (!AppendedString.includes(textbox.name)) {
AppendedString += ';' + textbox.name;
}
}
Codepen Link
You can’t initialize AppendedString as null otherwise, the includes() method won’t be available
otherwise, you can give each row a unique ID, and store in an array IDs that already have been clicked by the user.
var AppendedString = '';
var clickedRows = [];
function onChangeTest(textbox) {
if (!clickedRows.includes(textbox.id)) {
AppendedString += ';' + textbox.name;
clickedRows.push(textbox.id)
}
}
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!(arr.indexOf(nowS) > -1)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
Somewhat similar to your need,
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!arr.includes(nowS)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
You can add flag your textboxes and ignore if it's clicked again. Like using jquery you can do something like this:
function onChangeTest(textbox) {
AppendedString = AppendedString;
if (!textbox.hasClass("clicked")){
AppendedString = AppendedString + ';' + textbox.name;
textbox.AddClass("clicked");
}
}
I want to remove an element from the array ids if the element doesn't exist.
<div id="nl-form-0" >
<input type="text" id='dynamic_translation_0_0' value="15" />
<input type="text" id='dynamic_translation_0_1' value="15" />
<input type="text" id='dynamic_translation_0_2' value="15" />
<input type="text" id='dynamic_translation_1_2' value="15" />
</div>
ids = [
"transliterateTextarea",
"dynamic_translation_0_0",
"dynamic_translation_0_1",
"dynamic_translation_0_2",
"dynamic_translation_1_0",
"dynamic_translation_1_1",
"dynamic_translation_1_2"];
check_remove_ids_array(ids);
console.log(ids);
console.log($("#dynamic_translation_1_1").length);
function check_remove_ids_array(array_in) {
array_length = array_in.length;
for (n = 0; n <= array_length; n++) {
if ($("#" + array_in[n]).length == '0') {
removeValue(ids,array_in[n]);
}
}
}
function removeValue(arr, value) {
var array = arr;
for (var i = array.length-1; i--;) {
if (array[i] === value) {
array.splice(i, 1);
}
}
return array;
}
In the above code dynamic_translation_1_1 does not exist. I want to remove that or any other element from the array ids if the element doesn't exist
Why does/did it not work?
Basically you had a return and assigning problem. Since there are no reference parameters in JavaScript you have to assign the returned array back to the initial ids. Same goes for your removeValue() function.
Suggestion
Use the array.filter() prototype instead. It solves your problem more elegantly.
Example
<html>
<head>
<script src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script>
$(document).ready(function(){
ids = ["transliterateTextarea", "dynamic_translation_0_0", "dynamic_translation_0_1", "dynamic_translation_0_2", "dynamic_translation_1_0", "dynamic_translation_1_1", "dynamic_translation_1_2"];
ids = check_remove_ids_array(ids); //We have to assign it back, else we always get the initial ids array!
console.log(ids);
console.log($("#dynamic_translation_1_1").length);
});
function check_remove_ids_array(array_in){
array_length = array_in.length; //Is not required in this example anymore.
//We use the filter function instead.
return array_in.filter(function(item){return $("#" + item).length > 0})
};
</script>
</head>
<body>
<input type = 'text' id = 'dynamic_translation_0_0' value = '15' />
<input type = 'text' id = 'dynamic_translation_0_1' value = '15' />
<input type = 'text' id = 'dynamic_translation_0_2' value = '15' />
<input type = 'text' id = 'dynamic_translation_1_2' value = '15' />
</body>
</html>
This is my html:
<form>
<input type='text' name='campo1' value='valor0'/>
<input type='text' name='campo2' value='valor1'/>
<input type='text' name='campo3' value='valor2'/>
<input type='text' name='campo4' value='valor3'/>
<input type='text' name='campo5' value='valor4'/>
<input type='text' name='campo6' value='valor5'/>
<input type="button" onclick="inpt();">
</form>
I created a function to make a string and pass it to another function
The string contain all values for input text with match string 'campos' in the input name.
<script type="text/javascript">
var tags_inpt = new Array();
var param = "";;
function inpt() {
tags_inpt=document.getElementsByTagName('input');
var i;
for (i=0; i<tags_inpt.length; i++) {
if ((tags_inpt[i].type=='text')&&(tags_inpt[i].name.match(/campo/))){
param += '"' +tags_inpt[i].value +'",';
}
}
alert(param + '"A"'); // this print -> "valor0","valor1","valor2","valor3","valor4","valor5","A" OK!!
// call funcion2()
funcion2("valor0","valor1","valor2","valor3","valor4","valor5","A"); // this result in valor1 in funcion2() OK!!
funcion2(param + '"A"'); // this return 'undefined' --> BAD
}
function funcion2(a,b,c,d,e,f,g){
var z = b;
alert (z);
}
</script>
When use param variable to dynamically pass arguments to funcion2(), I get undefined value.
What is the correct way to make this?
Thanks
Try this:
funcion2.apply(window, (param + ',"A"').split(",") );
See the DEMO
Don't use string concatenation for this, that's prone to errors depending on your input. Use an array instead:
<script type="text/javascript">
function inpt() {
var tags_inpt = document.getElementsByTagName('input');
var matches = [];
for (var i=0; i<tags_inpt.length; ++i) {
if ((tags_inpt[i].type=='text') && (tags_inpt[i].name.match(/campo/))){
matches.push(tags_inpt[i].value);
}
}
matches.push('A');
funcion2.apply(this, matches);
}
function funcion2(a,b,c,d,e,f,g) {
var z = b;
alert (z);
}
</script>