I'm trying to compare the value of a form element with it's default text (set via the title attribute). If the VALUE == TITLE, change the value to a zero length string. However, I can't seem to make it work. I'm sure it's just my lack of experience with Javascript and jQuery. Many thanks.
HTML
<form name="results-form" id="results-form">
<input type="text" name="price-min" class="form-textbox-small no-radius defaultText" data="Minimum" title="Minimum" onchange="UpdateSearch()">
<input type="text" name="price-max" class="form-textbox-small no-radius defaultText" data="Maximum" title="Maximum" onchange="UpdateSearch()">
</form>
Javascript
function updateSearch(){
$.each($("#results-form").serializeArray(),function(){
console.log("value: "+this.value+" data: "+this.data+" title: "+this.title);
if(this.value == this.title){
this.value = '';
}
});
var FormData = $("#results-form :input[value!='']").serialize();
console.log(FormData);
$(".defaultText").blur();
}
$(document).ready(function () {
$(".defaultText").focus(function (srcc) {
if ($(this).val() == $(this)[0].title) {
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".defaultText").blur(function () {
if ($(this).val() == "") {
$(this).addClass("defaultTextActive");
$(this).val($(this)[0].title);
}
});
$(".defaultText").blur();
});
Console Output
value: 3 data: undefined title: undefined
value: Maximum data: undefined title: undefined
Try this:
var arr = $("#results-form").serializeArray();
$.each(arr, function (i, input) {
var value = input.value;
var $elem = $("[name='" + input.name + "']");
var data = $elem.attr('data');
var title = $elem.attr('title');
console.log("value: " + value + " data: " + data + " title: " + title );
// You can process the parameters here now
});
Related
I have a jquery autocomplete which is not doing anything. I have used the code from here. It works in their example.
There are some changes... First, array is created from a viewModelList and it works. here is a small part of it:
var suburbs = [
{
id: "17023",
suburb: "Epsom",
postCode: "3551",
state: "VIC"
},
{
id: "17024",
suburb: "Muskerry",
postCode: "3557",
state: "VIC"
}
I have endeavoured to use messages to indicate the respose - what it is but even the messages dont work... I cannot even get the response value..
I created a div below the form for the messages and they work having been tested using a click function.. I did try a ".change" function on the "#Suburbs" id and also got nothing..
Here is the code:
<script>
(function ($) {
$(function () {
var suburbs = [
#for (var i = 0; i < Model.SuburbAndPostcodesList.Count; i++) {
<text>{
id: "#Model.SuburbAndPostcodesList[i].SuburbsAndPostcodesId",
suburb: "#Model.SuburbAndPostcodesList[i].Suburb",
postCode: "#Model.SuburbAndPostcodesList[i].PostCode",
state: "#Model.SuburbAndPostcodesList[i].State.ShortName"
}#(i == Model.SuburbAndPostcodesList.Count - 1 ? "" : ",")</text>
}
];
$("#Suburb").autocomplete({
source: function (req, responseFn) {
addMessage("search on: '" + req.term + "'<br/>");
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
var a = $.grep(suburbs, function (item , index) {
//addMessage(" sniffing: '" + item + "'<br/>");
return matcher.test(item.suburb);
});
addMessage("Result: " + a.length + " items<br/>");
responseFn(a);
},
select: function (value, data) {
if (typeof data == "undefined") {
addMessage('You selected: ' + value + "<br/>");
} else {
addMessage('You selected: ' + data.item.value + "<br/>");
}
}
});
function addMessage(msg) {
$('#msgs').append(msg);
}
});
});
</script>
The id "#Suburb" is correct and worked for a simple version of .autocomplete.
EDIT: here is page code for the javascript.. Hope this is what you were after..
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo"></script>
<script src="/lib/jquery/dist/jquery.min.js"></script>
<script src="/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script src="/lib/jquery-ui/jquery-ui.js"></script>
<script>
(function ($) {
$(function () {
var suburbs = [
{
id: "17023",
suburb: "Epsom",
postCode: "3551",
state: "VIC"
},
{
id: "17024",
suburb: "Muskerry",
postCode: "3557",
state: "VIC"
},
...
{
id: "17055",
suburb: "Bonnet Hill",
postCode: "7053",
state: "TAS"
},
{
id: "17056",
suburb: "Wellington Park",
postCode: "7054",
state: "TAS"
}
];
$("#Suburb").autocomplete({
source: function (req, responseFn) {
addMessage("search on: '" + req.term + "'<br/>");
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
var a = $.grep(suburbs, function (item , index) {
//addMessage(" sniffing: '" + item + "'<br/>");
return matcher.test(item.suburb);
});
addMessage("Result: " + a.length + " items<br/>");
responseFn(a);
},
select: function (value, data) {
if (typeof data == "undefined") {
addMessage('You selected: ' + value + "<br/>");
} else {
addMessage('You selected: ' + data.item.value + "<br/>");
}
}
});
function addMessage(msg) {
$('#msgs').append(msg);
}
});
});
</script>
EDIT2: Here is the div element "suburb" as I think its probably a good idea to see what the autocomplete is working on.
<div class="form-group">
<label class="col-md-2 control-label" for="Suburb">Suburb:</label>
<div class="col-md-10">
<input class="form-control" type="text" data-val="true" data-val-required="A suburb name is required" id="Suburb" name="Suburb" value="Eaglehawk" />
<span class="text-danger field-validation-valid" data-valmsg-for="Suburb" data-valmsg-replace="true" />
</div>
</div>
Okay, a few things:
first: your jQuery .ready() function isn't running at all. You are combining several shorthand and advanced techniques, and they are not working. (More details on this in the comments below) Until you can do some research and get the concepts down, probably better to use the long-hand method, and just do
$(document).ready(function() {
});
Second: when you do $('#Suburb'), that means you have to have an element with id="Suburb" someplace in your document. Your input didn't have that.
Third: your a array that you are returning is an array of objects which your autocomplete won't recognize. You either need to return an array of strings, or an array of objects in this format: { label: "Choice1", value: "value1" }. The easiest way to accomplish this was just to add .map into your existing code, right after the .grep:
source: function (req, responseFn) {
addMessage("search on: '" + req.term + "'<br/>");
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
var a = $.grep(suburbs, function (item , index) {
return matcher.test(item.suburb);
});
a = $.map(a, function(x){
return x.suburb;
});
addMessage("Result: " + a.length + " items<br/>");
responseFn(a);
},
That being said, I have made some mods to your code (making some assumptions) and here is a working fiddle. Sorry, I had already started working on my own fiddle by the time you added yours. It was easier to just continue with the fiddle that I created than it was to modify yours.
I have code to find something from database and output it back if it exists.
Now when I output it back I need to make on click one of those outputs replace that output as var in some other var.
$(document).ready(function() {
$('#display').hide();
$("#leavepost").keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 35) {
$('#display').show();
$('#leavepost').on('keyup', function() {
var matches = $(this).val().match(/(^|\s)(#[a-z\d-]+)/ig)[0];
var name = matches;
$.ajax({
type: "POST",
url: "d/sul.php",
data: {
su: name
},
success: function(sss) {
$('#display').html(sss);
$(".adduser").click(function() {
var username = $(this).text();
var a = username;
var username2 = $(this).attr('id');
var E = "<a class='red' contenteditable='false' href='#' >" + a + "</a>";
var content = name.replace(name, E);
$("#leavepost").html(content);
$("#display").hide();
$("#leavepost").focus();
});
}
});
}).keyup();
}
});
});
When I click on class div hides but before that nothings happend... I need to replace #word from var name witdh var E.
Thanks
Your problem is most likely because you used .html() in on a <textarea> as stated in the discussion.
https://jsfiddle.net/q9gwdLj5/
$(function(){
$("#choices li").click(function(){
var name = $(this).text();
$("#ta").val($("#ta").val().replace("#thisperson", name));
})
})
Changing the .html() bit with .val() will fix the problem.
I have a jQuery function which execute when page is post back by using back button. But the dropdown value does not change when page is post back in the older version of Firefox. In older version it is just showing the default values when page is post back. Below is the jQuery function:
function loadData() {
try {
var URL = "/Home/LoadBackdata/" + new Date().getMilliseconds();
$.post(URL, null, function (data) {
debugger;
if (data != "") {
var backData = data.split(",");
if (backData[0] != "") {
$('#ConsignorAddressCountryId option').removeAttr('selected');
// [1]
$("#ConsignorAddressCountryId option[value=" + backData[0] +").prop('selected', true);
//ConsigneeAddressCountryId is the id of another class which consist of a dropdown
$('#ConsigneeAddressCountryId option').removeAttr('selected');
$("#ConsigneeAddressCountryId option[value=" + backData[3] +").prop('selected', true);
$('#drpQuantity option').removeAttr('selected');
$('#drpQuantity').prop('selectedIndex', ((parseInt(backData[13]) == 0) ? 0 : (parseInt(backData[13]) - 1)));
}
}
});
[1] is where I am removing the default selected value - ConsignorAddressCountryId is the id of the class which consist of a dropdown.
I have also tried some things. Below is the code:
function loadData() {
try {
var URL = "/Home/LoadBackdata/" + new Date().getMilliseconds();
$.post(URL, null, function (data) {
debugger;
if (data != "") {
var backData = data.split(",");
if (backData[0] != "") {
$('#ConsignorAddressCountryId option').removeAttr('selected');
$("#ConsignorAddressCountryId").find('option:Selected').removeAttr("selected");
document.getElementById('ConsignorAddressCountryId').selectedIndex = -1;
var ttt = $("#ConsignorAddressCountryId option[value=" + backData[0] + "]").text();
$("#dvQuoteFrom >div >a >span >.selectBox-label").first().text("ttt");
$("#ConsignorAddressCountryId option[value=" + backData[0] + "]").prop('selected', true);
$('#ConsigneeAddressCountryId option').removeAttr('selected');
document.getElementById('ConsigneeAddressCountryId').selectedIndex = -1;
var Consignee = $("#ConsigneeAddressCountryId option[value=" + backData[0] + "]").text();
$("#dvQuoteTo >div >a >span >.selectBox-label").first().text(Consignee);
$("#ConsigneeAddressCountryId option[value=" + backData[3] + "]").prop('selected', true);
$("#drpQuantity").find('option:Selected').removeAttr("selected");
document.getElementById('drpQuantity').selectedIndex = -1;
var Quantity = $("#drpQuantity option[value=" + backData[13] + "]").text();
$("#divQuantity>a >span >.selectBox-label").first().text(parseInt(10));
$('#drpQuantity').prop('selectedIndex', ((parseInt(backData[13]) == 0) ? 0 : (parseInt(backData[13]) - 1)));
}
}
});
But it still nor working in older versions of Firefox.
Try to use reset function like to remove selected :
$('#yourdropdownid').reset();
And to set selected value, you can user val() like :
$('#yourdropdownid').val(your value);
The following Javascript dynamically adds another Select box 'on change' of the original select box. The issue I am having is that when it creates the new select box it gives it the same 'name' and 'id' as the original select box. Therefore when I do a submit action on the form, the last selectbox is the only value submitted. How can I change the 'name' and/or the 'id' attributes of the newly created select box? Honestly I am VERY new to Javascript so if this is an easy fix I do apologize. Thank you ALL in advance!
$(function () {
var values = new Array();
$(document).on('change', '.form-group-multiple-selects .input-group-multiple-select:last-child select', function () {
var selectsLength = $('.form-group-multiple-selects .input-group-multiple-select select').length;
var optionsLength = ($(this).find('option').length);
var sInputGroupHtml = $(this).parent().html();
var sInputGroupClasses = $(this).parent().attr('class');
$(this).parent().parent().append('<div class="' + sInputGroupClasses + '">' + sInputGroupHtml + '</div>');
updateValues();
});
$(document).on('change', '.form-group-multiple-selects .input-group-multiple-select:not(:last-child) select', function () {
updateValues();
});
$(document).on('click', '.input-group-addon-remove', function () {
$(this).parent().remove();
updateValues();
});
function updateValues() {
values = new Array();
$('.form-group-multiple-selects .input-group-multiple-select select').each(function () {
var value = $(this).val();
if (value != 0 && value != "") {
values.push(value);
}
});
$('.form-group-multiple-selects .input-group-multiple-select select').find('option').each(function () {
var optionValue = $(this).val();
var selectValue = $(this).parent().val();
});
}
function in_array(needle, haystack) {
var found = 0;
for (var i = 0, length = haystack.length; i < length; i++) {
if (haystack[i] == needle) return i;
found++;
}
return -1;
}
})
have you considered using an array for the select boxes?
The first one, and any that follow can be
<select name="example[]"></select>
And then simply process the array on form submission, you can check for the size and then do a foreach loop if the size is > 1
I'am using Ajax call to load on-change value from database into text-area with all values and their quantity in one text-area. Now I want to change this text-area value to change when I entered a value in another text-box and multiply with all quantity value of text-area.
I am new to JavaScript and ajax so help me guys. Here is my code.
$(document).ready(function () {
$('#location').change(function () {
$.ajax({
url: 'location.php?location=' + $(this).val(),
type: "get",
timeout: 10000,
dataType: 'json',
success: function (data) {
var material_name = data.material_name;
var material_quantity = data.product_quantity;
var data_material = "";
for(var i = 0; i < material_name.length; i++) {
data_material += material_name[i] + " : " + material_quantity[i] + " ";
}
document.getElementById("material_name").value = data_material;
document.getElementById("material_quantity1").value = data.product_quantity;
},
error: function () {}
});
$('#quantity').keyup(function () {
var price = document.getElementById('material_quantity').value;
//document.getElementById("price_hidden").value=price;
var quantity = document.getElementById("quantity").value;
var total = quantity * price;
document.getElementById("total").value = total;
document.getElementById("total_hidden").value = document.getElementById("total").value;
});
});
});
I want to change all values of text-box with ID #material_quantity1 value when I entered any quantity in other text-box.
Like in my textbox I have 15,20,25 now if I entered 5 then it will show 75,100,125.
$('#textarea1').live('blur',function(){ // Textarea in which you will enter the value..
var textarea1 = $('#textarea').val(); // Textarea which will contain 152025..
// if your value containts commas then you can use $('#textarea').val().replace(/,/g , ""); instead of $('#textarea').val();
var final_value = $(this).val()*textarea1; // Put this value in the textarea you want...
});
//Add the below function this will replace your numbers with commas
function ReplaceNumberWithCommas(param1) {
var x=param1.toString();
var lastThree = x.substring(x.length-3);
var otherNumbers = x.substring(0,x.length-3);
if(otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
return res;
}