using jquery or javascript - javascript

I have this code in my page. with two textboxes and one textarea.
<fieldset>
<legend><b>Search Criteria</b></legend>
<table>
<tr>
<td>
Find Text:
<input type="text" style="width:150px" id="txtFind"/>
<input type="button" id="btnfind" value=" Find "/>
</td>
</tr>
<tr>
<td>
Replace Text:
<input type="text" style="width:150px" id="Text1"/>
<input type="button" value="Replace Text" id="btnReplace"/>
</td>
</tr>
</table>
</fieldset>
<br />
<fieldset>
<legend><b>Result</b></legend>
<table>
<tr>
<td>
<%:Html.TextArea("Hello ASP.NET here")%>
</td>
</tr>
</table>
</fieldset>
in my first textbox if I enter "here" then I click the Find button it should find the text
if I enter "MVC" on second text box click Replace Text button it should replace the text "here" to "MVC" ("Hello ASP.NET MVC").,
Please can any one help me out? How to do this with javascript or jquery?
Thanks

Asuming your textarea has id="textarea", you should do this:
$("#btnfind").click(function(){
var find = $("#txtFind").val();
var replace = $("Text1").val();
var text = $("#textarea").val();
while(text.indexOf(find) >= 0){
text = text.replace(find, replace);
}
$("#textarea").val(text);
});
(Note that we're not using Regular expressions to replace because the text to find is dynamic so we'd have to escape the 'find' text).
Hope this helps. Cheers

this should get you started: http://jsfiddle.net/DD7t5/
using jQuery and a highlight jQuery plugin
var $result = $('#result'),
$txtFind = $('#txtFind'),
$txtReplace = $('#txtReplace');
$('#btnFind').click(function() {
$result.removeHighlight();
var findValue = $txtFind.val();
if (findValue.length > 0) {
$result.highlight(findValue) // find and highlight
}
});
$('#btnReplace').click(function() {
$result.text($result.text().replace(eval('/' + $txtFind.val() + '/gi'),
$txtReplace.val())); // replace
});

Related

Handling forms with multiple actions

Let's say I have an Admin page with a list of items, and I have various capabilities to modify those records -- Change its name, Delete it, Clear its contents, etc. For example a row would be rendered similar to the following:
const row =`<tr id="id${this.id}">
<td name="name">
<input type="text" placeholder="Set name" value=${this.name} />
<input type="submit" name="setName" value="Save" />
</td>
<td name="size">${this.set.size}<td/>
<td name="elements"><b>{ ${this.renderSetElements()} }</td>
<td name="actions">
<input type="text" placeholder="Add element" />
<input type="submit" name="addElement" value="Add" />
<input type="submit" name="clearElements" value="Clear" />
<input type="submit" name="deleteSet" value="Delete" />
</td>
</tr>`
What would the proper way to add forms here? Should there be one form around the row? Should there be four forms per row -- one for each action? (setName, addElement, clearElements, deleteSet)? Or what is the suggested way to accomplish the above? Additionally, is identifying the row as id${this.id} appropriate, or what's usually the contention for something like that?
The short answer is that you can have a
The form inside a cell td.
<table>
<tr><td><form>...</form></td></tr>
<tr><td><form>...</form></td></tr>
</table>
You can have a table inside a form
<form>
<table>
<tr><td>...</td></tr>
<tr><td>...</td></tr>
</table>
</form>
Or you can ditch the form element and use JavaScript to do Ajax:
In this case, I will be using the Javascript library jQuery since it simplifies a lot of stuff; however, you can implement this with pure Javascript if you want to.
// Wait for the document to be fully loaded
$(document).ready(function(){
$(".submit").on("click", function(event){
event.preventDefault();
console.log("submit...");
var url = "https://httpbin.org/get";
var data = {
id: $('#id').val()
};
$.get(url, data, function(result){
console.log("Server received the id number: ", result.args.id);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input class="inputs" id="id" value="0"/></td>
</tr>
<tr>
<td><button class="submit" id="add">Add</button></td>
</tr>
</table>
In your particular case, you might try generate these rows dynamically and using Ajax to send the information to the server, without having to refresh the whole page. Here is an example:
(function(){
let count = 0;
function createColumn(){
let column = $('<td>');
let text = $(`<input type="text" placeholder="Set name" value="${count}">`);
let submit = $('<button class="save" type="submit" name="setName">Save</button>');
column.append(text);
column.append(submit);
return column;
}
function createRow(){
let row = $('<tr>');
row.attr("id", count++);
row.append(createColumn());
return row;
}
let table = $('#table');
$('#btnAdd').on('click', () => {
table.append(createRow());
});
table.on('click', '.save', function() {
let text = $(this).prev().val();
console.log("INPUT TEXT:", text);
});
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnAdd">Add Row</button>
<table id="table">
</table>
I hope you found this informative, useful, and that you can apply it to your particular issue.

Clear contents of multiple input fields?

Hi I am dynamically adding rows with a button and when I am finished entering information, I would like it to then clear the contents. The button "Add Pokemon" is the one I want to press and it should clear all the contents.
function addPokemon() {
var pokemonName = document.getElementById("pokemon-name-container");
pokemonName.innerHTML = document.getElementById("pokemon-names").value;
for (var i = 0; i < element.length; i++) {
if (element[i].value !== "undefined") {
pokemonArray.push(element[i].value);
}
}
console.log(pokemonArray);
for (var i = 0; i < pokemonArray.length; i++) {
document.getElementById("pokemon-container").innerHTML += "<li>" + pokemonArray[i] + "</li>";
}
document.getElementById("pokemon-name-container").value = "";
document.getElementById("move-name").value = "";
}
This is my function I am using. ^^
And below is my HTML vv
<div>
<table>
<tbody id="tbody">
<tr>
<td>
<div id="pokemon-name-container">
<p>Pok&eacutemon Name:</p>
<input type="text" id="pokemon-names" size="30">
</td>
</tr>
<tr>
<td>
<p class="moves">Moves:</p>
</td>
</tr>
<tr>
<td>
<input class="move-container" type="text" id="move-name" placeholder="Enter move here">
</td>
<td>
<input class="button-container" type="button" id="remove-btn" value="Remove Move" onclick="removeRow()">
</td>
</tr>
</tbody>
</table>
</div>
<div>
<input type="button" class="add-move-button" id="add-move-button" value="Add Move" onclick="addRow()">
</div>
<div>
<input type="button" class="add-pokemon-button" id="add-pokemon-button" value="Add Pokémon" onclick="addPokemon()">
</div>
You could put to all the inputs you create a unique class that defines them under a parent with a unique id. Then use inside the function of javascript the next pice of code const childs = document.querySelectorAll('#idParent.classChilds') this querySelectorAll is kind of like the getElementsById but uses selectors of CSS so it's more powerfull. The querySelectorAll returns you a NodeList of all the elements that matches de DOM with the CSS query.
Then you would only need to do something similar to this using functional programming:
const childs = document.querySelectorAll('#idParent .classChilds')
childs.forEach(child=>{
child.value = ""
})
I'm not sure if this code works (I'm not with an code editor and a browser to check if there isn't mistakes), as I said, you could do something similar to it
HOPE IS HELPFULL
FYI, try to avoid the selectors like getElementById or getElementsByClass....
Try to use this:
document.querySelector('CSS SELECTOR') // GIVES YOU THE FIRST MATCH OF THE CSS SELECTOR
document.querySelectorAll('CSS SELECTOR') // GIVES YOU A NODELIST WITH ALL MATCHES

On Button Click, how do I change row with span to input and focus each input using angularjs

I have a table, with 2 labels/inputs (i use a ng-show/ng-hide which works with the edit button), and 2 buttons (1 button is edit, and 1 button is delete). What i want to do is when the user clicks the edit button, it should hide the spans and shows the inputs(textboxes) and focus on the first input. If the user clicks outside of either inputs, (in my opinion, loses focus which mean using blur method), then the inputs should turn back to span with the updated values. Here is what I have created, but I can't figure out the rest. New to angular so any help will be appreciated and voted.
This is the html code:
<table class="tableGV">
<tbody>
<tr>
<td class="DisplayRowData">
<span class="LabelText" data-ng-hide="data1">{{data1}}</span>
<input class="DataText" type="text"data-ng-show="showEditMode" maxLength="1" data-ng-model="editData1" ng-change="cs.ClassCode"/>
</td>
<td class="DisplayRowData">
<span class="LabelText" data-ng-hide="data2">{{data2}}</span>
<input class="DataText" type="text" data-ng-show="data2" maxlength="50" data-ng-model="data2" />
</td>
<td align="right">
<button type="button" id = "btnEditClassService{{$index}}" data-ng-click="edit(cs, $index)" class="editButton"></button>
<button type="button" id = "btnDeleteClassService{{$index}}" data-ng-click="delete(cs, $index)" class="deleteButton"></button>
</tr>
</tbody>
</table>
after this, i am not sure where to go. Thanks for anyone to help me.
you can check this plnkr. The solution is not elegant but I think it sastify your requirement.
function onEdit(){
vm.isEdit = true;
executeAfterDOMRender(function(){
document.getElementById('txt1').focus()
});
}
function onBlur(){
executeAfterDOMRender(function(){
var txtIds = ['txt1', 'txt2'];
var activeElementId = document.activeElement.id;
if(~txtIds.indexOf(activeElementId)){
//txt boxes is focued, do nothing here
} else {
vm.isEdit = false;
}
});
}
function executeAfterDOMRender(callback){
$timeout(callback);
}

Jquery selecting inputs with adjacent asterisk

Using jquery, I'm trying to select those inputs that have an asterisk adjacent to them.
HTML
<form name="checkout">
<table width="100%" border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="FirstName" value="" />*</td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="LastName" value="" /></td>
</tr>
</table>
</form>
Jquery
var elems = $("form[name='checkout'] :input").filter(function(index) {
var str = $(this).parents('td').html()
return (str.indexOf("*")!=-1)
}).length;
Result of elems should be 1 but it's not working, i.e. the form submits in spite of a return false in the handler so can't seem to catch the error details. What am I doing wrong?
var elems = $("td:contains('*') input");
This is selector for the input elements that you need.
elems.length will give you 1 in this case
Ha Ha,
Missing the onReady().
Use this one,
$(function(){
var elems = $("form[name='checkout'] :input").filter(function(index) {
var str = $(this).parents('td').html()
return (str.indexOf("*")!=-1)
}).length;
console.log(elems);
});
That should do. Cheers :).
I suggest you to use CSS :after pseudo element
<style>
.mandatory:after{
content:"*";
}
</style>
<span class="mandatroy">
<input type="text" name="FirstName" value="">
</span>
<script>
$("form[name='checkout'] .mandatory > :input")
</script>
It would be easier, if you added a class to the inputs which have an asterisk after them:
<td><input type="text" name="FirstName" class="required" />*</td>
Then you could select them by their class and do whatever you wish to them.
$("input.required").length();
Given the explicit requirement:
$('input').filter(function () {
return (this.nextSibling && this.nextSibling.nodeValue.indexOf('*') > -1) || (this.previousSibling && this.previousSibling.nodeValue.indexOf('*') > -1);
}).css('border-color','#f00');
JS Fiddle demo.

dynamically generate textboxes using JavaScript

I want generate textboxes dynamically according to user input. If user enter the integer value in the textbox, if he/she enter 5 i want generate 5 textboxes. This code is working in Firefox but not working in IE and Netscape; please help me how to do this or point out any other mistake in this code to me. Also, the technology we are using is Struts 2.
Please help me.
JavaScript code:
function generate()
{
var tot = document.getElementById("totmob").value;
var tbl = document.getElementById("sim");
for(var i =1;i<=tot;i++)
{
tbl.innerHTML = 'Mobile No'+i+' <input type="text" size = "20" maxlength= "20" name= hoardingregister.mobileno> <br> \n';
}
HTML code:
<td>
<s:textfield id="totmob" label="Total Mobile Number" />
<td>
<td>
<input type="button" value="ADD" onclick="generate()"/>
</td>
</tr>
</table>
<div id="sim">
</div>
for(var i =1;i<=tot;i++)
{
tbl.innerHTML = 'Mobile No'+i+' <input type="text" size = "20" maxlength= "20" name= hoardingregister.mobileno> <br> \n';
}
should be
for(var i =1;i<=tot;i++)
{
tbl.innerHTML += 'Mobile No'+i+' <input type="text" size = "20" maxlength= "20" name= hoardingregister.mobileno> <br> \n';
}
because you need to append to the inner HTML, rather than replace it.
You've also used a <td> instead of a </td>
Can you try something else than InnerHtml - you can try this:
use GetElementByID to get the element you want to add text boxes to
remove any existing child items if required
Add textboxes as child items to the selected node
From your javascript code, it looks you should use following code:
tbl.innerHTML +=
instead of
tbl.innerHTML =
inside the for loop.
The code below works perfect for me in IE as well as Firefox. When you say It's nt working, what do you mean ?
function generate()
{
var tot = document.getElementById("totmob").value;
var tbl = document.getElementById("sim");
for(var i =1;i<=tot;i++)
{
tbl.innerHTML = tbl.innerHTML +'Mobile No'+i+' <input type="text" size = "20" maxlength= "20" name= hoardingregister.mobileno> <br> \n';
}
}
</script>
<body>
<table>
<tr>
<td>
<span>Total Mobile Number </span>
<input type="text" id="totmob" />
<td>
<td>
<input type="button" value="ADD" onclick="generate()"/>
</td>
</tr>
</table>
<div id="sim">
</div>
</body>
</html>
add a unique identifier to the name of the input or a unique id to it.
like:
for(var i =1;i<=tot;i++)
{
tbl.innerHTML += 'Mobile No'+i+' <input type="text" size = "20" maxlength= "20" name= hoardingregister.mobileno'+i+'> <br> \n';
}
or you put a id into it like:
id="input"+i
But if you are changing the value in the text box without refreshing the page more text boxes are adding after the previously added text box. But it is wrong whenever we change the value in the text box only tat number of new text boxes should be added instead of keeping the previous text boxes too. Can you please change the coding according to the conditions I said.

Categories