set new element into list with jquery - javascript

i try to add a new li element into the list with jquery.
In this example it´s work fine, but when i want to get the value of a input field
with .val() it´s not create a li element.
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_append
my code: http://jsfiddle.net/k1acpxtp/
$(document).ready(function(){
/* Click Event für Button "btn2" */
$('#btn2').click(function(){
/* Fügt ein Elemente in die Liste mit ".append" und
mit ".val()", wird das Value des Input Feldes ausgelesen */
$("ol").append($("#test").val());
});
});

Just change the code to this :
$("ol").append("<li>"+$("#test").val()+"</li>);

You're appending text to an ol element, which is invalid. You need to first create the li, set its text then append that to the ol:
$('#btn2').click(function () {
$('<li />', { text: $('#test').val() }).appendTo('ol');
});
Example fiddle

try with this code( change code where you append value in ol )
$("ol").append("<li>"+$("#test").val()+"</li>);

Use this code instead
$("ol").append("<li>"+$("#test").val()+"</li>);

Try this
$('#btn2').click(function(){
$("ol").append('<li>'+$("#test").val()+'</li>');
});
Working Demo

I'd suggest the following:
$(document).ready(function() {
$('#btn2').click(function(e) {
// preventing the default behaviour of the <button>:
e.preventDefault();
var entered = $('#test').val(),
tag;
// naive check to see if the user entered 'proper' HTML, eg:
// <li>, <li>Some content</li> etc:
if (entered.indexOf('<') === 0 && entered.lastIndexOf('>') === (entered.length - 1)) {
tag = entered;
} else {
// otherwise, if they entered 'li', 'LI' etc, we
// wrap the entered-value with the '<' and '>' to
// form an HTML tag:
tag = '<' + entered + '>';
}
// creating the element, then appending it to
// the <ol>:
$(tag).appendTo('ol');
});
});
$(document).ready(function() {
$('#btn2').click(function(e) {
e.preventDefault();
var entered = $('#test').val(),
tag;
if (entered.indexOf('<') === 0 && entered.lastIndexOf('>') === (entered.length - 1)) {
tag = entered;
} else {
tag = '<' + entered + '>';
}
$(tag).appendTo('ol');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol></ol>
<form method="post" action="create.html">New Track:
<input type="text" id="test" name="track" placeholder="<tagName>" />
</form>
<button id="btn2">Add Element</button>
Note that I've also added a placeholder attribute to provide guidance for filling in the <input />.
Note that this also does not check validity of the elements you're adding; therefore it will allow you, or your users, to append a <div> to the <ol>, regardless of that action creating invalid HTML.
It may be worth adjusting so that the <li> is created automatically, but the content is supplied by the users:
$(document).ready(function() {
$('#btn2').click(function(e) {
e.preventDefault();
var entered = $('#test').val();
// creating an <li> element:
$('<li>', {
// taking the entered-value to set the element's
// innerHTML:
'html': entered
}).appendTo('ol');
});
});
$(document).ready(function() {
$('#btn2').click(function(e) {
e.preventDefault();
var entered = $('#test').val();
$('<li>', {
'html': entered
}).appendTo('ol');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol></ol>
<form method="post" action="create.html">New Track:
<input type="text" id="test" name="track" placeholder="new content" />
</form>
<button id="btn2">Add Element</button>
References:
appendTo().
event.preventDefault().

Related

Unable to get the value of the clicked button when two button elements shared the same name [duplicate]

I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I'd like to know which submit button was clicked without applying a .click() event to each one.
Here's the setup:
<html>
<head>
<title>jQuery research: forms</title>
<script type='text/javascript' src='../jquery-1.5.2.min.js'></script>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var me = event.currentTarget;
var data = me.data.value;
var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
</script>
</head>
<body>
<h2>Here's my form:</h2>
<form action='nothing' method='post' name='testform'>
<input type='hidden' name='data' value='blahdatayadda' />
<input type='submit' name='name1' value='value1' />
<input type='submit' name='name2' value='value2' />
</form>
</body>
</html>
Live example on jsfiddle
Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?
I asked this same question: How can I get the button that caused the submit from the form submit event?
I ended up coming up with this solution and it worked pretty well:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val();
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
In your case with multiple forms you may need to tweak this a bit but it should still apply
I found that this worked.
$(document).ready(function() {
$( "form" ).submit(function () {
// Get the submit button element
var btn = $(this).find("input[type=submit]:focus" );
});
}
This works for me:
$("form").submit(function() {
// Print the value of the button that was clicked
console.log($(document.activeElement).val());
}
When the form is submitted:
document.activeElement will give you the submit button that was clicked.
document.activeElement.getAttribute('value') will give you that button's value.
Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."
There is a native property, submitter, on the SubmitEvent interface.
Standard Web API:
var btnClicked = event.submitter;
jQuery:
var btnClicked = event.originalEvent.submitter;
Here's the approach that seems cleaner for my purposes.
First, for any and all forms:
$('form').click(function(event) {
$(this).data('clicked',$(event.target))
});
When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.
Then, in $('form').submit(), you can inquire what was last clicked, with something like
if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();
Wow, some solutions can get complicated! If you don't mind using a simple global, just take advantage of the fact that the input button click event fires first. One could further filter the $('input') selector for one of many forms by using $('#myForm input').
$(document).ready(function(){
var clkBtn = "";
$('input[type="submit"]').click(function(evt) {
clkBtn = evt.target.id;
});
$("#myForm").submit(function(evt) {
var btnID = clkBtn;
alert("form submitted; button id=" + btnID);
});
});
I have found the best solution is
$(document.activeElement).attr('id')
This not only works on inputs, but it also works on button tags.
Also it gets the id of the button.
Another possible solution is to add a hidden field in your form:
<input type="hidden" id="btaction"/>
Then in the ready function add functions to record what key was pressed:
$('form#myForm #btnSubmit').click(function() {
$('form#myForm #btaction').val(0);
});
$('form#myForm #btnSubmitAndSend').click(function() {
$('form#myForm #btaction').val(1);
});
$('form#myForm #btnDelete').click(function() {
$('form#myForm #btaction').val(2);
});
Now in the form submition handler read the hidden variable and decide based on it:
var act = $('form#myForm #btaction').val();
Building on what Stan and yann-h did but this one defaults to the first button. The beauty of this overall approach is that it picks up both the click and the enter key (even if the focus was not on the button. If you need to allow enter in the form, then just respond to this when a button is focused (i.e. Stan's answer). In my case, I wanted to allow enter to submit the form even if the user's current focus was on the text box.
I was also using a 'name' attribute rather than 'id' but this is the same approach.
var pressedButtonName =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
$(":input[type=submit]:first")[0].name :
$(":input[type=submit]:focus")[0].name;
This one worked for me
$('#Form').submit(function(){
var btn= $(this).find("input[type=submit]:focus").val();
alert('you have clicked '+ btn);
}
Here is my solution:
$('#form').submit(function(e){
console.log($('#'+e.originalEvent.submitter.id));
e.preventDefault();
});
If what you mean by not adding a .click event is that you don't want to have separate handlers for those events, you could handle all clicks (submits) in one function:
$(document).ready(function(){
$('input[type="submit"]').click( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var input = $(event.currentTarget);
var which_button = event.currentTarget.value;
var data = input.parents("form")[0].data.value;
// var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute
$(document).on('click', '[type=submit]', function() {
var form = $(this).prop('form') || $(this).closest('form')[0];
$(form.elements).filter('[type=submit]').removeAttr('clicked')
$(this).attr('clicked', true);
});
$('form').on('submit', function() {
var submitter = $(this.elements).filter('[clicked]');
})
You can simply get the event object when you submit the form. From that, get the submitter object. As below:
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
}
In case you want to send this form to the backend, you can create a new form element by new FormData() and set the key-value pair for which button was pressed, then access it in the backend. Something like this -
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let form = $(this);
let newForm = new FormData($(form)[0]);
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
if (submitter_btn.attr("name") == "approve_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else if (submitter_btn.attr("name") == "reject_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else {
console.log("there is some error!");
return;
}
}
I was basically trying to have a form where user can either approve or disapprove/ reject a product for further processes in a task.
My HTML form is something like this -
<form method="POST" action="{% url 'tasks:review-task' taskid=product.task_id.id %}"
class="review-form">
{% csrf_token %}
<input type="hidden" name="product_id" value="{{product.product_id}}" />
<input type="hidden" name="task_id" value="{{product.task_id_id}}" />
<button type="submit" name="approve_btn" class="btn btn-link" id="approve-btn">
<i class="fa fa-check" style="color: rgb(63, 245, 63);"></i>
</button>
<button type="submit" name="reject_btn" class="btn btn-link" id="reject-btn">
<i class="fa fa-times" style="color: red;"></i>
</button>
</form>
Let me know if you have any doubts.
Try this:
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){
// This is the ID of the clicked button
var clicked_button_id = event.originalEvent.submitter.id;
});
});
$("form input[type=submit]").click(function() {
$("<input />")
.attr('type', 'hidden')
.attr('name', $(this).attr('name'))
.attr('value', $(this).attr('value'))
.appendTo(this)
});
add hidden field
For me, the best solutions was this:
$(form).submit(function(e){
// Get the button that was clicked
var submit = $(this.id).context.activeElement;
// You can get its name like this
alert(submit.name)
// You can get its attributes like this too
alert($(submit).attr('class'))
});
Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.
$('form.form-js').submit(function(event){
var frm = $(this);
var btn = $(document.activeElement);
if(
btn.length &&
frm.has(btn) &&
btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
btn.is('[name]')
){
frm.append('<input type="hidden" id="form-js-temp" name="' + btn.attr('name') + '" value="' + btn.val() + '">');
}
// Handle the form submit here
$('#form-js-temp').remove();
});
Side note: I personally add the class form-js on all forms that are submitted via JavaScript.
Similar to Stan answer but :
if you have more than one button, you have to get only the
first button => [0]
if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId
$(document).on('submit', function(event) {
event.preventDefault();
var pressedButtonId =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
"myDefaultButtonId" :
$(":input[type=submit]:focus")[0].id;
...
}
This is the solution used by me and work very well:
// prevent enter key on some elements to prevent to submit the form
function stopRKey(evt) {
evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
var alloved_enter_on_type = ['textarea'];
if ((evt.keyCode == 13) && ((node.id == "") || ($.inArray(node.type, alloved_enter_on_type) < 0))) {
return false;
}
}
$(document).ready(function() {
document.onkeypress = stopRKey;
// catch the id of submit button and store-it to the form
$("form").each(function() {
var that = $(this);
// define context and reference
/* for each of the submit-inputs - in each of the forms on
the page - assign click and keypress event */
$("input:submit,button", that).bind("click keypress", function(e) {
// store the id of the submit-input on it's enclosing form
that.data("callerid", this.id);
});
});
$("#form1").submit(function(e) {
var origin_id = $(e.target).data("callerid");
alert(origin_id);
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="form1" name="form1" action="" method="post">
<input type="text" name="text1" />
<input type="submit" id="button1" value="Submit1" name="button1" />
<button type="submit" id="button2" name="button2">
Submit2
</button>
<input type="submit" id="button3" value="Submit3" name="button3" />
</form>
This works for me to get the active button
var val = document.activeElement.textContent;
It helped me https://stackoverflow.com/a/17805011/1029257
Form submited only after submit button was clicked.
var theBtn = $(':focus');
if(theBtn.is(':submit'))
{
// ....
return true;
}
return false;
I was able to use jQuery originalEvent.submitter on Chrome with an ASP.Net Core web app:
My .cshtml form:
<div class="form-group" id="buttons_grp">
<button type="submit" name="submitButton" value="Approve" class="btn btn-success">Approve</button>
<button type="submit" name="submitButton" value="Reject" class="btn btn-danger">Reject</button>
<button type="submit" name="submitButton" value="Save" class="btn btn-primary">Save</button>
...
The jQuery submit handler:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function() {
...
// Ensure that we log an explanatory comment if "Reject"
$('#update_task_form').on('submit', function (e) {
let text = e.originalEvent.submitter.textContent;
if (text == "Reject") {
// Do stuff...
}
});
...
The jQuery Microsoft bundled with my ASP.Net Core environment is v3.3.1.
Let's say I have these "submit" buttons:
<button type="submit" name="submitButton" id="update" value="UpdateRecord" class="btn btn-primary">Update Record</button>
<button type="submit" name="submitButton" id="review_info" value="ReviewInfo" class="btn btn-warning sme_only">Review Info</button>
<button type="submit" name="submitButton" id="need_more_info" value="NeedMoreInfo" class="btn btn-warning sme_only">Need More Info</button>
And this "submit" event handler:
$('#my_form').on('submit', function (e) {
let x1 = $(this).find("input[type=submit]:focus");
let x2 = e.originalEvent.submitter.textContent;
Either expression works. If I click the first button, both "x1" and "x2" return Update Record.
I also made a solution, and it works quite well:
It uses jQuery and CSS
First, I made a quick CSS class, this can be embedded or in a seperate file.
<style type='text/css'>
.Clicked {
/*No Attributes*/
}
</style>
Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).
// Adds a CSS Class to the Button That Has Been Clicked.
$("form :input[type='submit']").click(function ()
{
if ($(this).hasClass("Clicked"))
{
$(this).removeClass("Clicked");
}
$(this).addClass("Clicked");
});
Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.
// On Form Submit
$("form").submit(function ()
{
// Test Which Button Has the Class
if ($("input[name='name1']").hasClass("Clicked"))
{
// Button 'name1' has been clicked.
}
else
{
// Button 'name2' has been clicked.
}
});
Hope this helps!
Cheers!
You can create input type="hidden" as holder for a button id information.
<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">
In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.
A simple way to distinguish which <button> or <input type="button"...> is pressed, is by checking their 'id':
$("button").click(function() {
var id = $(this).attr('id');
...
});
Here is a sample, that uses this.form to get the correct form the submit is into, and data fields to store the last clicked/focused element. I also wrapped submit code inside a timeout to be sure click events happen before it is executed (some users reported in comments that on Chrome sometimes a click event is fired after a submit).
Works when navigating both with keys and with mouse/fingers without counting on browsers to send a click event on RETURN key (doesn't hurt though), I added an event handler for focus events for buttons and fields.
You might add buttons of type="submit" to the items that save themselves when clicked.
In the demo I set a red border to show the selected item and an alert that shows name and value/label.
Here is the FIDDLE
And here is the (same) code:
Javascript:
$("form").submit(function(e) {
e.preventDefault();
// Use this for rare/buggy cases when click event is sent after submit
setTimeout(function() {
var $this=$(this);
var lastFocus = $this.data("lastFocus");
var $defaultSubmit=null;
if(lastFocus) $defaultSubmit=$(lastFocus);
if(!$defaultSubmit || !$defaultSubmit.is("input[type=submit]")) {
// If for some reason we don't have a submit, find one (the first)
$defaultSubmit=$(this).find("input[type=submit]").first();
}
if($defaultSubmit) {
var submitName=$defaultSubmit.attr("name");
var submitLabel=$defaultSubmit.val();
// Just a demo, set hilite and alert
doSomethingWith($defaultSubmit);
setTimeout(function() {alert("Submitted "+submitName+": '"+submitLabel+"'")},1000);
} else {
// There were no submit in the form
}
}.bind(this),0);
});
$("form input").focus(function() {
$(this.form).data("lastFocus", this);
});
$("form input").click(function() {
$(this.form).data("lastFocus", this);
});
// Just a demo, setting hilite
function doSomethingWith($aSelectedEl) {
$aSelectedEl.css({"border":"4px solid red"});
setTimeout(function() { $aSelectedEl.removeAttr("style"); },1000);
}
DUMMY HTML:
<form>
<input type="text" name="testtextortexttest" value="Whatever you write, sir."/>
<input type="text" name="moretesttextormoretexttest" value="Whatever you write, again, sir."/>
<input type="submit" name="test1" value="Action 1"/>
<input type="submit" name="test2" value="Action 2"/>
<input type="submit" name="test3" value="Action 3"/>
<input type="submit" name="test4" value="Action 4"/>
<input type="submit" name="test5" value="Action 5"/>
</form>
DUMB CSS:
input {display:block}
I write this function that helps me
var PupulateFormData= function (elem) {
var arr = {};
$(elem).find("input[name],select[name],button[name]:focus,input[type='submit']:focus").each(function () {
arr[$(this).attr("name")] = $(this).val();
});
return arr;
};
and then Use
var data= PupulateFormData($("form"));

trying to add a checkbox dynamically with jquery but nothing apepars

Just trying to create a very basic to-do app and for whatever reason, my checkboxes are not showing up.
html:
<div class="todo-box">
<input id="first-contact" type="text" placeholder="what do you have to do?"></input>
<button>submit</button>
<div id="list-section">
</div>
</div>
and jquery:
$( document ).ready(function() {
$('button').on('click', function() {
var a = $('#first-contact').val().toLowerCase();
$('<p>').attr('class', 'list-item').append(a).appendTo('#list-section');
$('<input>', {type: "checkbox"}).appendTo('#list-item');
var pAmount = $('#list-section').children().length;
if (pAmount > 6) {
$('#list-section p').last().remove();
}
});
});
You have 2 issues in $('<input>', {type: "checkbox"}).appendTo('#list-item');:
you're using {type: "checkbox"} at the place where jQuery $() expects a domain argument: you must build a complete element in first argument instead
you're appending the element to a list-item id while you created it as a class
This will work:
$( document ).ready(function() {
$('button').on('click', function() {
var a = $('#first-contact').val().toLowerCase();
$('<p>').attr('class', 'list-item').append(a).appendTo('#list-section');
$('<input type="checkbox">').appendTo('.list-item:last');
var pAmount = $('#list-section').children().length;
if (pAmount > 6) {
$('#list-section p').last().remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="todo-box">
<input id="first-contact" type="text" placeholder="what do you have to do?"></input>
<button>submit</button>
<div id="list-section">
</div>
</div>
EDIT: modified in response to the OP's comment : added :last modifier to make checkbox added to the just newly created item only.
I think this is what you are going for?
$('button').on('click', function() {
var a = $('#first-contact').val().toLowerCase();
// update here
$('#list-section').append("<p><input type='checkbox' value='"+a+"'></p>");
var pAmount = $('#list-section').children().length;
if (pAmount > 6) {
$('#list-section p').last().remove();
}
});

how to filter using jquery

html
<div class="adds">
<input type="text" value="" class="ip1" id="ip1" />
<input type="button" value="ADD" class="btn1" id="btn1" />
</br>
<div class="add">
<ul class="justList">
<li>police</li>
</ul>
</div>
</div>
<div class="filter">
<input type="text" value="" class="ip2" id="ip2" />
<input type="button" value="Filter" class="btn2" id="btn2" />
<div class="filter">
<ul>
</ul>
</div>
</div>
JS
$(document).ready(function(){
$("#btn1").on("click",function(){
var occ = $("#ip1").val();
if(occ.length)
{
$('<li />', {html: occ}).appendTo('ul.justList')
$("#ip1").val('');
}
});
});
Hi Here if i give "xxxx" and click "ADD" button the text ll append in the list of ul li, i need if i click filter i need only text that equal to what i gave second input box. it should filter all "xxxx" and it must show only that. any one help me.
See if this code works
$("#btn2").click(function () {
var value = $("#ip2").val();
$(".justList li").each(function () {
var curr_text = $(this).text();
if (curr_text == value)
console.log("equal");
else
$(this).hide();
});
});
Working Code:JSFIDDLE
You can try this using jQueries :contains selector :
$("#btn2").on("click", function () {
var occ = $("#ip2").val();
if (occ.length) {
$matches = $('.justList li:contains("'+occ+'")');
$matches.show();
$('.justList li').not($matches).hide();
}
else{
$('.justList li').show();
}
});
Demo
Update
If you want a case insensitive filter, you can create custome jQuery selector by adding the following script:
jQuery.expr[':'].Contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
and use it in the previous script.
Demo
For a filter, use jQuery filter. That is designed for this type of work.
The function passed to filter receives each element in turn and if you return true it retains it. if you return false it removes it.
Partial string matching:
It also uses match with a case-insensitive RegEx (so you can specify POL, pol or Pol and still match police in your example):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Wu2x3/2/
$("#btn2").on("click", function () {
var occ = $("#ip2").val();
var $li = $('.justList li');
if (occ.length) {
// Hide all, then show matches
$li.hide();
$li.filter(function(){
// return true if case-insensitive match occurs
return $(this).text().match(new RegExp(occ, "i"));
}).show();
}
else{
// Show everything
$li.show();
}
});
This converts the text values to lowercase before comparison to make the check case-insensitive.
*Note: These solutions will also work with strings containing quotes
Whole string matching:
If you want to match the full string only (bit odd for a filter, but as you specified):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Wu2x3/4/
$("#btn2").on("click", function () {
var occ = $("#ip2").val();
var $li = $('.justList li');
if (occ.length) {
occ = occ.toLowerCase();
// Hide all, then show matches
$li.hide();
$li.filter(function(){
// return true if case-insensitive match occurs
return $(this).text().toLowerCase() == occ;
}).show();
}
else{
// Show everything
$li.show();
}
});

Supply new code to a DIV if content within it is removed

I wonder if it's possible in jQuery/JS:
If “foobar” is removed or gone from the HTML code
<div id="foo">
<div id="line1">...</div>
<div id="line2">foobar</div>
</div>
I'd like to automatically add “new”
<div id="foo">
<div id="line1">...</div>
<div id="line2">new</div>
</div>
I'd like to have "new" displayed when someone deleted "foobar" from #line2. It's for attribution purposes.
If you make the text the value of an input you can bind to it's change event:
<div id="foo">
<div id="line1">...</div>
<div id="line2"><input type="text" value="foobar" /></div>
</div>
$('#line2').children('input').on('change', function () {
var $this = $(this);
if ($this.val() == '') {
$this.val('new');
}
});
Here is a demo: http://jsfiddle.net/u9Twu/
Note that if you want to programatically change the value of the input you have to manually call .trigger('change') on the input after you change it's value for the change event handler to run.
Also note that .on() is new in jQuery 1.7 and in this case is the same as .bind().
UPDATE
var $foo = $('#foo'),
$line2 = $foo.children('#line2');
if ($line2.length == 0) {
//no #line2 element is found
$foo.append('<div id="line2">new</div>');
} else if ($line2.text().length == '') {
//#line2 element is empty
$line2.text('new');
} else if ($line2.text() != 'foobar') {
//#line2 element does not contain only the string: foobar
$line2.text('new');
}
Here is a demo: http://jsfiddle.net/u9Twu/1/
$('#foo').click(function() {
$('#line2').remove();
$(this).append('<div id="line3">new foobar</div>');
})
http://jsfiddle.net/y5FDs/

adjusting default value script to work with multiple rows

I am using a default value script (jquery.defaultvalue.js) to add default text to various input fields on a form:
<script type='text/javascript'>
jQuery(function($) {
$("#name, #email, #organisation, #position").defaultvalue("Name", "Email", "Organisation", "Position");
});
</script>
The form looks like this:
<form method="post" name="booking" action="bookingengine.php">
<p><input type="text" name="name[]" id="name">
<input type="text" name="email[]" id="email">
<input type="text" name="organisation[]" id="organisation">
<input type="text" name="position[]" id="position">
<span class="remove">Remove</span></p>
<p><span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" /></p>
</form>
I am also using a script so that users can dynamically add (clone) rows to the form:
<script>
$(document).ready(function() {
$(".add").click(function() {
var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
x.find('input').each(function() { this.value = ''; });
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
});
</script>
So, when the page loads there is one row with the default values. The user would then start adding information to the inputs. I am wondering if there is a way of having the default values show up in subsequent rows that are added as well.
You can see the form in action here.
Thanks,
Nick
Just call .defaultValue this once the new row is created. The below assumes the format of the columns is precticable/remains the same.
$(".add").click(function() {
var x = $("form > p:first-child");
x.clone(true).insertBefore("form > p:last-child");
x.find('input:not(:submit)').defaultvalue("Name", "Email", "Organisation", "Position");
return false;
});
You should remove ids from the input fields because once these are cloned, the ids, classes, everything about the elements are cloned. So you'll basically end up with multiple elements in the DOM with the same id -- not good.
A better "set defaults"
Personally I would remove the "set defaults plugin" if it's used purely on the site for this purpose. It can easily be re-created with the below and this is more efficient because it doesn't care about ordering of input elements.
var defaults = {
'name[]': 'Name',
'email[]': 'Email',
'organisation[]': 'Organisation',
'position[]': 'Position'
};
var setDefaults = function(inputElements)
{
$(inputElements).each(function() {
var d = defaults[this.name];
if (d && d.length)
{
this.value = d;
$(this).data('isDefault', true);
}
});
};
Then you can simply do (once page is loaded):
setDefaults(jQuery('form[name=booking] input'));
And once a row is added:
$(".add").click(function() {
var x = $("form > p:first-child");
x.clone(true).insertBefore("form > p:last-child");
setDefaults(x.find('input')); // <-- let the magic begin
return false;
});
For the toggling of default values you can simply delegate events and with the help of setDefault
// Toggles
$('form[name=booking]').delegate('input', {
'focus': function() {
if ($(this).data('isDefault'))
$(this).val('').removeData('isDefault');
},
'blur': function() {
if (!this.value.length) setDefaults(this);
}
});
Fiddle: http://jsfiddle.net/garreh/zEmhS/3/ (shows correct toggling of default values)
Okey, first of all; ids must be unique so change your ids to classes if you intend to have more then one of them.
and then in your add function before your "return false":
var
inputs = x.getElementsByTagName('input'),
defaults = ["Name", "Email", "Organisation", "Position"];
for(var i in inputs){
if(typeof inputs[i] == 'object'){
$(inputs[i]).defaultvalue(defaults[i]);
}
}

Categories

Resources