Jquery search table td last character of string - javascript

if i search 'abc' tan result is like 'testoneabc.com,testtwoabc.com,hwvdhgabc.com'
but my code search like this https://drive.google.com/file/d/0B9uqoluJ-ZTLYnlxQmZqVjNuYjg/view?usp=drivesdk
but i want like this https://drive.google.com/file/d/0B9uqoluJ-ZTLWXJ6dmFWZlNka2M/view?usp=drivesdk
HTML:
<table>
<tr><th>Unique ID</th><th>Random ID</th></tr>
<tr><td>testabc.com</td><td>442</td></tr>
<tr><td>teerfrestabc.com</td><td>556</td></tr>
<tr><td>teerfsderestabc.com</td><td>4666</td></tr>
<tr><td>teerasdefrestabc.com</td><td>334</td></tr>
<tr><td>teerfrestabcdsad.com</td><td>54364</td></tr>
</table>
<br />
<input type="text" id="search" placeholder=" live search"></input>
Script:
$("#search").on("keyup", function() {
var value = $(this).val();
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) !== 0) {
$row.hide();
}
else {
$row.show();
}
}
});
});
This code shows result like this

Related

Angularjs devade tags when user put comma

I have a case in which I need to divide tags when the user put a comma separation, for the moment the user can only add tags one by one, what I want to do is allows user to enter more than one tag in the input separated by a comma:
This is what I have now :
this is what I want to do :
what I have so far :
<div class="form-group">
<label>Mes centres d'intérêt</label>
<div class="input-group" style="margin-bottom: 8px;">
<input id="tagInsert" type="text" name="newTag" ng-model="newTag" ng-model-options="{debounce: 100}" typeahead="tag for tag in getTags($viewValue)" class="form-control" typeahead-loading="loadingTags" ng-keydown="addInterestOnEvent($event)" ng-disabled="interestLimit" autocomplete="off">
<span class="input-group-btn"><span class="btn btn-primary" ng-click="addInterest()" analytics-on="click" ng-disabled="interestLimit" analytics-event="Ajout Interet" analytics-category="Profil">Ajouter</span></span>
</div>
<p class="form__field__error" ng-show="interestLimit">Vous avez atteint la limite de 10 centres d'intérêt.</p>
<ul class="tags">
<li class="tag" ng-repeat="name in user.interests track by $index">{{ name }} <i class="icon-close" ng-click="removeInterest($index)" analytics-on analytics-event="Supprimer Interet" analytics-category="Profil"></i></li>
</ul>
</div>
My controller :
$scope.getTags = function (name) {
return $http.get('/api/tags/' + name.replace('/', '')).then(function (result) {
var tags = result.data;
for (var i = tags.length; i--; ) {
var tagName = tags[i].name;
if ($scope.user.interests.indexOf(tagName) !== -1) tags.splice(i, 1);
else tags[i] = tagName;
}
return tags;
});
};
$scope.removeInterest = function (id) {
$scope.interestLimit = false;
$scope.user.interests.splice(id, 1);
}
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value;
if (value.length) {
element.value = '';
if ($scope.user.interests.indexOf(value) === -1) {
$scope.user.interests.push(value);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
};
$scope.addInterestOnEvent = function (event) {
if (event.which !== 13) return;
event.preventDefault();
$scope.addInterest();
};
$scope.remove = function () {
$scope.confirmModal = Modal.confirm.delete(function () {
User.remove(function () {
submit = true;
Auth.logout();
$location.path('/');
});
})('votre compte');
};
You should split value with comma and do for loop.
Change "addInterest" function like this:
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value.split(',');
if (value.length) {
element.value = '';
for (var i = 0; i < value.length; i++) {
if ($scope.interestLimit) break;
if ($scope.user.interests.indexOf(value[i]) === -1) {
$scope.user.interests.push(value[i]);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
}
};
As far as I understand , you want to split text into string array by comma
Try this code please
<input id='tags' type="text" />
<input type="button" value="Click" onclick="seperateText()" />
<script>
function seperateText(){
var text= document.getElementById("tags").value;
var tags = text.split(',');
console.log(text);
console.log(tags);
}
</script>

Disable Select Option if already selected

I have created a table which clones its last row if all the text boxes are filled and select is changed in the previous row. I am trying to add a condition that the newly dropdown options should be disabled if they were already selected in previous rows .
Demo Fillde
disable option code:
$('select').change(function() {
var value = $(this).val();
$(this).siblings('select').children('option').each(function() {
if ( $(this).val() === value ) {
$(this).attr('disabled', true).siblings().removeAttr('disabled');
}
});
});
Full JS:
$('#results').append('<table width="100%" border="1" cellspacing="0" cellpadding="5" id="productanddates" class="border"> <tr><td> <input type="text" name="to1" id="to1" value="" /> </td> <td> <select class="dd" name="Phonenumberdd1" id="Phonenumberdd1"> <option value="test">test </option><option value="test2">test 2</option></select></td> <td> <input type="text" name="renewal_by1" id="renewal_by1" /> </td> <td> <input type="text" name="Renivaul_to1" id="Renivaul_to1" value="" /> </td></TR></TABLE>'
);
$('select').change(function() {
var value = $(this).val();
$(this).siblings('select').children('option').each(function() {
if ( $(this).val() === value ) {
$(this).attr('disabled', true).siblings().removeAttr('disabled');
}
});
});
$('#results').on('focus', ':input', function() {
$(this).closest('tr').filter(function() {
return !$(this).data('saved');
})
.find(':input').each(function() {
$(this).data('value', this.value);
$(this).closest('tr').data('saved', true);
});
})
.on('input change', ':input', function() {
$(this).data('filled', this.value != $(this).data('value'))
var tr = $(this).closest('tr');
all = tr.find(':input'),
fld = all.filter(function() {
return $(this).data('filled');
});
if( all.length == fld.length ) {
if( !tr.data('done') ) {
$('#buttonclck')[0].click();
tr.data('done', true);
}
} else {
if( tr.data('done') ) {
tr.data('done', false);
}
}
});
$('#buttonclck').on('click', function () {
var lastRow = $('#productanddates').closest('#productanddates').find("tr:last-child");
var lastRowInputs = lastRow.find('input');
var isClone = false;
lastRowInputs.each(function() {
if($(this).val().length) {
isClone = true;
}
});
if(!isClone)
return false;
var cloned = lastRow.clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
var regIdMatch = /^(.+)(\d+)$/;
var aIdParts = id.match(regIdMatch);
var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
$(this).attr('id', newId);
$(this).attr('name', newId);
});
cloned.find("input[type='text']").val('');
cloned.insertAfter(lastRow);
});
HTML:
<div id="results"></div>
<input id="buttonclck" type="button" class="hide" value="button"/>
Your mistake was here:
$(this).siblings('select').children('option').each(function() { ... }
It should be :
$(this).children('option').each(function() { ... }
Why do you select siblings of the select element? You should directly descend to its options. I do not know if it is intended, but such code will make option disabled in both rows: previous and newly generated.
Here is the fiddle:
http://jsfiddle.net/99pvwypp/19/

Dynamically Clone or create the row only if the first row data is filled and the dropdown state is change

Below code Creates the html table and creates a static row and then on button click the same row is created but my problem is i don't want to
create or clone the row on button click
the row should be created on if the data of textbox(s) of that row are not null and the select value is not test then a new row needs to be created beneath that row .
Js fiddle demo
HTML:
<div id="results"></div>
<input id="buttonclck" type="button" value="button"/>
JS:
$('#results').append('<table width="100%" border="1" cellspacing="0" cellpadding="5" id="productanddates" class="border"> <tr><td> <input type="text" name="to1" id="to1" value="" /> </td> <td> <select name="Phonenumberdd1" id="Phonenumberdd1"> <option value="test">test </option> <option value="demo">demo</option></select></td> <td> <input type="text" name="renewal_by1" id="renewal_by1" /> </td> <td> <input type="text" name="Renivaul_to1" id="Renivaul_to1" value="" /> </td></TR></TABLE>'
);
$('#buttonclck').on('click', function () {
var lastRow = $('#productanddates').closest('#productanddates').find("tr:last-child");
var cloned = lastRow.clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
var regIdMatch = /^(.+)(\d+)$/;
var aIdParts = id.match(regIdMatch);
var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
$(this).attr('id', newId);
$(this).attr('name', newId);
});
cloned.find("input[type='text']").val('');
cloned.insertAfter(lastRow);
});
You can use this approach
When a form element is focused check and save current state of all form elements
Once content of a form element changes set data-filled to true for that element, see if all elements on current row have data-filled set.
If data-filled is set, if that row's data-done attribute is not set to true then add new row and set rows data-done attribute to true
Since all the rows are added dynamically, delegated events would be used.
$('#results').append('<table width="100%" border="1" cellspacing="0" cellpadding="5" id="productanddates" class="border"> <tr><td> <input type="text" name="to1" id="to1" value="" /> </td> <td> <select name="Phonenumberdd1" id="Phonenumberdd1"> <option value="test">test </option><option value="test2">test 2</option></select></td> <td> <input type="text" name="renewal_by1" id="renewal_by1" /> </td> <td> <input type="text" name="Renivaul_to1" id="Renivaul_to1" value="" /> </td></TR></TABLE>'
);
$('#results').on('focus', ':input', function() {
$(this).closest('tr').filter(function() {
return !$(this).data('saved');
})
.find(':input').each(function() {
$(this).data('value', this.value);
$(this).closest('tr').data('saved', true);
});
})
.on('input change', ':input', function() {
$(this).data('filled', this.value != $(this).data('value'))
var tr = $(this).closest('tr');
all = tr.find(':input'),
fld = all.filter(function() {
return $(this).data('filled');
});
if( all.length == fld.length ) {
if( !tr.data('done') ) {
$('#buttonclck')[0].click();
tr.data('done', true);
}
} else {
if( tr.data('done') ) {
tr.next('tr').remove();
tr.data('done', false);
}
}
});
$('#buttonclck').on('click', function () {
var lastRow = $('#productanddates').closest('#productanddates').find("tr:last-child");
var cloned = lastRow.clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
var regIdMatch = /^(.+)(\d+)$/;
var aIdParts = id.match(regIdMatch);
var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
$(this).attr('id', newId);
$(this).attr('name', newId);
});
cloned.find("input[type='text']").val('');
cloned.insertAfter(lastRow);
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div>
<input id="buttonclck" type="button" class="hide" value="button"/>
Try this - work only for first input (is example)
http://jsfiddle.net/xegnt0uh/1/
$('#buttonclck').on('click', function () {
var lastRow = $('#productanddates').closest('#productanddates').find("tr:last-child");
//eg. if input[0] value isnt ""
if(lastRow.find('input')[0].value !== "") {
var cloned = lastRow.clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
var regIdMatch = /^(.+)(\d+)$/;
var aIdParts = id.match(regIdMatch);
var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
$(this).attr('id', newId);
$(this).attr('name', newId);
});
cloned.find("input[type='text']").val('');
cloned.insertAfter(lastRow);
}
});
I renamed select to selectbox
$('#buttonclck').on('click', function () {
var lastRow = $('#productanddates').find("tr:last-child");
var selectLastRow = lastRow.find('select[name=selectbox]').val(); // <-- add this select value
if(typeof selectLastRow !== 'undefined' && selectLastRow != '' && selectLastRow != 'test') { // <-- add this condition
var cloned = lastRow.clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
var regIdMatch = /^(.+)(\d+)$/;
var aIdParts = id.match(regIdMatch);
var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
$(this).attr('id', newId);
// $(this).attr('name', newId); // REMOVE THIS BECAUSE WE FIND IN TR
});
cloned.find("input[type='text']").val('');
cloned.insertAfter(lastRow);
}
});
DEMO JSFIDDLE
EDIT
-------
if all the condition are met a same new row to be created below that
so on
so set number of empty inputs
var emptyInputs = lastRow.find('.input').filter(function () { return this.value.length == 0; }).length;
and modify condition like below
if(typeof selectLastRow !== 'undefined'
&& selectLastRow != ''
&& selectLastRow != 'test'
&& emptyInputs == 0
) { ....
DEMO2 JSFIDDLE

How to apply a class attribute to an HTML string (not rendered on the document)

I am am developing code for am automator to improve the project with several pages.
I have a textarea input where I can enter HTML and it shows me the HTML with the right structure.
HTML:
<textarea name="message">
<input type="text" value="TextTwo" id="texttwo"/>
<input type="text" value="DataOne" id="dataone"/>
<input type="text" value="NumberTwo" id="numbertwo"/>
<input type="text" value="TextOne" id="textone"/>
<input type="text" value="DataTwo" id="datatwo"/>
<input type="text" value="NumberOne" id="numberone"/>
</textarea>
<button>process</button>
JS/JQuery:
$('button').click(function () {
var code = $('textarea[name=message]').val();
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(code);
});
I would like to apply classes following these rules:
The input that has the word "Text" value in applying the class = "text"
The input that has the word "Data" value in applying the class = "data"
The input that has the word "Number" value in applying the class = "number"
An example of how the code would output in textarea
<input type="text" value="TextTwo" id="texttwo" class="text" />
<input type="text" value="DataOne" id="dataone" class="data" />
<input type="text" value="NumberTwo" id="numbertwo" class="number" />
<input type="text" value="TextOne" id="textone" class="text"/>
<input type="text" value="DataTwo" id="datatwo" class="data" />
<input type="text" value="NumberOne" id="numberone" class="number" />
DEMO CODE
What is a good approach to do this using JQuery?
I updated your fiddle and had this code working -- Can't give you a link since I don't actually have a fiddle account:
$('button').click(function () {
var code = $('textarea[name=message]').val();
// The best thing to do here is to turn that string of HTML into
// DOM elements and let the browser do the work.
var elms = jQuery.parseHTML(code);
var result = "";
// Now that we've processed the HTML into an array, work with it.
for (var i = 0; i < elms.length; i++) {
var el = elms[i];
if (el.tagName && el.tagName.toLowerCase() === "input") {
// Great! We we have an 'input' element.
var val = el.value;
if (val.indexOf("Text") !== -1) {
el.className = "text";
}
if (val.indexOf("Data") !== -1) {
el.className = "data";
}
if (val.indexOf("Number") !== -1) {
el.className = "number";
}
}
if (el.nodeType === 3) {
// Handle text nodes
result += el.nodeValue;
} else {
result += el.outerHTML;
}
}
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(result);
});
Under the assumption that all the html in the textarea is valid, What we can do is just build the html into a div and then format the html with jQuery. After this is done just get the content and put it in the textarea.
$('button').click(function () {
var code = $('textarea[name=message]').val(),
$code = $('<div />').html(code),
classes = {'Text': 'text', 'Data': 'data', 'Number': 'number'};
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('input', $code).each(function(){
var t = this,
$t = $(this);
for(key in classes){
if(t.value.indexOf(key) > -1){
$t.addClass(classes[key]);
return;
}
}
});
$('#output').val($code.html());
});
http://jsfiddle.net/LC5y3/4/
DEMO
$('button').click(function () {
var code = $.parseHTML($('textarea[name=message]').val());
console.log(code);
var newCode = "";
code = $.grep(code, function (n, i) {
if (n.nodeValue) {
return n.nodeValue.trim()
} else {
return (n.outerHTML && n.outerHTML.trim())
}
});
for (var i = 0; i < code.length; i++) {
var element=$(code[i]);
element.addClass(element.attr("type"));
newCode += code[i].outerHTML;
}
console.log(newCode);
console.log(code);
if (!$('#output').length) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(newCode);
});
You can use the attribute contains selector.
jsFiddle
$('input[id*="text"]').addClass('text');
$('input[id*="number"]').addClass('number');
$('input[id*="data"]').addClass('data');
You can dynamically build the elements:
$('input').addClass('className').attr('value','number');

Opening input when writing #Q# in textarea

I have textarea. Now, I want to do that once you write "#q + number#" ( e.g. #q1# ), it will create new input field.
For example if you write: "Hello my name is #q1# and my favorite food is #q2#". It will open two input fields.
And when you delete one of those #q + number#, it will delete the same field that was intended to the #q#
For example: if you write "Hello my name is #q1# and my favorite food is #q2#, and the input fields look like that:
<input type="text" q="1" />
<input type="text" q="2" />
and next that I delete the #q1# it supposed to look like that:
and don't delete the value of q="2" input.
How can I do that in jQuery/JavaScript?
Take a look at this quick fiddle http://jsfiddle.net/NgxvP/1/
Here you have something to start playing with
<html>
<head>
<style>
#inputField { position:relative;
width: 200px;
height: 200px;
background-color: #cda;
}
</style>
<script src="jquery-1.7.1.min.js"></script>
<script>
// in_array function provided by phpjs.org
function in_array (needle, haystack, argStrict)
{
var key = '',
strict = !! argStrict;
if (strict)
{
for (key in haystack)
{
if (haystack[key] === needle)
{
return true;
}
}
}
else
{
for (key in haystack)
{
if (haystack[key] == needle)
{
return true;
}
}
}
return false;
}
var addedFields = new Array();
function checkFields(input, charCode)
{
var text = (charCode) ? input.value + String.fromCharCode(charCode) : input.value;
var pattern = /#q[0-9]#/g;
var matches = text.match(pattern);
if (!matches) { matches = new Array(); }
if (addedFields.length>0 && addedFields.length != matches.length)
{
for (var index in addedFields)
{
if (!in_array('#q'+ index +'#', matches))
{
$('#q'+index).remove();
delete addedFields[index];
}
}
}
if (matches)
{
for (var i=0; i<matches.length; i++)
{
var code = matches[i];
var index = code.match(/[0-9]/)[0];
if ( $('#q'+index).length == 0 )
{
addFields(index);
}
}
}
}
function addFields(i)
{
addedFields[i] = true;
var fields = '';
for (var index in addedFields)
{
fields += '<input type="text" q="'+ index +'" id="q'+ index +'" />';
}
$('#inputField').html(fields);
}
</script>
</head>
<body>
<div id="formID">
<form>
<textarea onkeypress="checkFields(this, event.charCode); return true;" onkeyup="checkFields(this); return true;"></textarea>
<div id="inputField"></div>
</form>
</div>
</body>
</html>
EDITED: to avoid appending unordered input text fields, but showing them always ordered by their index, as commented in dfsq answer
I created a jsfiddle for your convenience http://jsfiddle.net/2HA5s/

Categories

Resources