Convert Jquery to Vanilla Script [duplicate] - javascript

This question already has answers here:
Is there an easy way to convert jquery code to javascript? [closed]
(5 answers)
Closed 4 months ago.
Is it possible to rewrite the following code into pure javascript? I don't want to use jquery.
$(function () {
var aggregateInput = function () {
var value = ('Website Url: ') + jQuery('input[name="url"]').val() + ' \n \n' +
('Subject: ') + jQuery('input[name="subject"] \n').val() + ' \n \n' +
('Brief Message: ') + jQuery('textarea[name="customer service"] \n \n').val().replace(/\n/g, '<br/>');
jQuery('textarea[name="email-message"]').val(value);
}
jQuery('.contact-style').on('keyup', aggregateInput);
});
$(document).ready(function () {
$('.contact-form-button-submit').attr('disabled', true);
$('.customform-message').keyup(function () {
if ($(this).val().length != 0) {
$('.contact-form-button-submit').attr('disabled', false);
} else {
$('.contact-form-button-submit').attr('disabled', true);
}
})
});

document.addEventListener('DOMContentLoaded', function () {
var aggregateInput = function () {
var value = ('Website Url: ') + document.querySelector('input[name="url"]').value + ' \n \n' +
('Subject: ') + document.querySelector('input[name="subject"] \n').value + ' \n \n' +
('Brief Message: ') + document.querySelector('textarea[name="customer service"] \n \n').value.replace(/\n/g, '<br/>');
document.querySelector('textarea[name="email-message"]').value = value;
}
document.querySelector('.contact-style').addEventListener('keyup', aggregateInput);
});
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('.contact-form-button-submit').setAttribute('disabled', true);
document.querySelector('.customform-message').addEventListener('keyup', function () {
if (this.value.length != 0) {
document.querySelector('.contact-form-button-submit').setAttribute('disabled', false);
} else {
document.querySelector('.contact-form-button-submit').setAttribute('disabled', true);
}
});
});

Related

Javascript weird if else not working [duplicate]

This question already has answers here:
Javascript string/integer comparisons
(9 answers)
Closed 6 years ago.
Anyone knows why showToast always pops up even if desiredquantity is greater than inventoryCount?
function checkavailable(){
var desiredquantity = document.getElementById("bin-Qty").value;
var inventoryCount = document.getElementById("bin-binItem-quantity").value;
var itemName = document.getElementById("bin-binItem").value;
if(desiredquantity > inventoryCount)
{
console.log(desiredquantity);
showToast('There are only ' +inventoryCount +' '+itemName+' left');
}
else
{
addToTransfer();
}
}
I have a button to that calls checkavailable
<button type="button"
onclick ="checkavailable();">
</button>
Please convert it to number first
Like this
if (+desiredquantity > +inventoryCount) { // + will parse it as number
console.log(desiredquantity);
showToast('There are only ' + inventoryCount + ' ' + itemName + ' left');
} else {
addToTransfer();
}
Or you can use parseInt if value is integer and if value float than use parseFloat
Like this
if (parseInt(desiredquantity) > parseInt(inventoryCount)) {
console.log(desiredquantity);
showToast('There are only ' + inventoryCount + ' ' + itemName + ' left');
} else {
addToTransfer();
}

JS Removing Labels Font Style - MVC3

I have a label which displays the number of characters used in a textbox. When the page first loads it looks fine as it is small and in italics. I am using Bootstrap for that styling.
<label id="lblCharactersRemaining"><small><em>0 Out Of 255 Characters</em></small></label>
My JavaScript checks and updates the text in this label with the number of characters a user enters, this also works fine.
The problem is that each time the JS activates the styling goes back to the default MVC type. How can I make sure that when the JS executes that it doesn't remove the Bootstrap styling?
My JS is:
<script type="text/javascript">
var maximumLength = '#System.Configuration.ConfigurationManager.AppSettings["MaximumTextBoxLength"]';
if (document.getElementById("ObjectTextBox")) {
var txtbox = document.getElementById("ObjectTextBox");
txtbox.onkeyup = function () { IsMaxLength(this); };
}
function IsMaxLength(objTxtCtrl) {
if (objTxtCtrl.getAttribute && objTxtCtrl.value.length > maximumLength) {
objTxtCtrl.value = objTxtCtrl.value.substring(0, maximumLength);
}
if (document.all) {
document.getElementById('lblCharactersRemaining').innerText = (objTxtCtrl.value.length) + ' Out Of ' + maximumLength + ' Characters';
}
else {
document.getElementById('lblCharactersRemaining').textContent = (objTxtCtrl.value.length) + ' Out Of ' + maximumLength + ' Characters';
}
if (objTxtCtrl.value.length == 0) {
document.getElementById('lblCharactersRemaining').textContent = '0 Out Of ' + maximumLength;
}
}
</script>
Try :
function IsMaxLength(objTxtCtrl) {
if (objTxtCtrl.getAttribute && objTxtCtrl.value.length > maximumLength) {
objTxtCtrl.value = objTxtCtrl.value.substring(0, maximumLength);
}
if (document.all) {
$('#lblCharactersRemaining').html('<small><em>' + objTxtCtrl.value.length + ' Out Of ' + maximumLength + ' Characters</em></small>');
}
else {
$('#lblCharactersRemaining').html('<small><em>' + objTxtCtrl.value.length + ' Out Of ' + maximumLength + ' Characters</em></small>');
}
if (objTxtCtrl.value.length == 0) {
$('#lblCharactersRemaining').html('<small><em>0 Out Of ' + maximumLength + '</em></small>');
}
}
Every time you launch the function, it deleted the tags 'small' and 'em', so just add them...
UPDATE : PS : Using Jquery language...
UPDATE AFTER COMMENT :
BOOTPLY : http://bootply.com/106485
CODE :
JS :
$('button.jquery').on('click', function(){
$('#lblCharactersRemaining').html('<small><em>0 Out Of 85200</em></small>');
});
$('button.nojquery').on('click', function(){
document.getElementById('lblCharactersRemaining').innerHTML = '<small><em>0 Out Of 666</em></small>';
});
HTML :
<label id="lblCharactersRemaining"><small><em>0 Out Of 255 Characters</em></small></label>
<button class="jquery">Change label with jquery</button>
<button class="nojquery">Change label without jquery syntax</button>

Submit can't see return false;

I know that I must add return false; to function called in onsubmit (I added it to function and onsubmit="" in HTML). But it doesn't work... Page freshing after pressing Enter or clicking submit button.
JavaScript generated forms:
AnswersHTML += "<div><form onsubmit='cheking(this," + a + "," + b + ", this); return false;'><input class='put' type='text' size='40'><input type='submit' value='Проверить'></form>
and function
function checking(answer, nums, numq, what) {
var usr = answer;
if (isNaN(answer)) {
usr = answer.value;
if (answer.value.length == "") {
usr = "Вы ничего не ввели!"
}
else {
answer = answer.value.toLowerCase();
}
}
if (answer == correct[nums][numq]) {
$(what).parent().parent().append("<br><span class='right'>Ответ: " + usr + "<br>Правильно!</span>").slideDown();
$(what).parent().parent().find(".put").remove();
$("#board").animate({ backgroundColor: '#2ecc71'});
$("#board").animate({ backgroundColor: '#f1c40f'}, 1000);
if (isPhysics[nums][numq]) {
physics++;
$("#presult").text(physics);
}
else {
life++;
$("#lresult").text(life);
}
}
else {
$("#board").animate({ backgroundColor: '#e74c3c'});
$("#board").animate({ backgroundColor: '#f1c40f'}, 1000);
var desciptionToWrong = "<br>" + description[nums][numq];
if (description[nums][numq] == false) {
desciptionToWrong = ""
}
$(what).parent().parent().append("<br><span class='wrong'>Ответ: " + usr + "<br>Неправильно!" + desciptionToWrong + "</span>")
$(what).parent().parent().find(".put").remove();
$(what).remove(".pressenter");
}
return false;
}
Sorry for my possibly disgusting code
Here's the full page https://rawgithub.com/ruslankh/Kurchatovy/master/index.html
Problem in function because when I'm replaced function to just alert, it was fine
Its probably due to type. You have wrong spelling in function call that would cause an error and call goes to server.
Change
'cheking(this," + a + "," + b + ", this);
To
'checking(this," + a + "," + b + ", this);
Your inline onclick has a typo, you left one of the c's out of the function name. This error likely terminates the click handler before it gets as far as the return statement.
Try this,
AnswersHTML += "<div><form data-a='"+a+"' data-b='"+b+"' class='myform'><input class='put... "
SCRIPT
$(function(){
$(document).on('submit','form.myform',function(){
checking(this, $(this).data('a'), $(this).data('b'), this);
return false;
});
});

How to get the URL parameters after redirecting using javascript?

After replacign the location with new parameters, the page after loaded doesn't get the paramaters value, despite there are values in the parameters
the used code is :
function getURLParameter(name) {
return
decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
}
$(document).ready(function () {
$(".sub").slideUp();
var div = getURLParameter("div");
var ddl = getURLParameter("ddl");
alert(div);
// alert("ManageTrainingNeeds.aspx?div=" + div + "&ddl=" + ddl);
// $("#" + div).slideDown();
// $("#ddlObjectiveGroup").val("'" + ddl + "'");
});
$(".btnAddSub").live("click", function () {
var diva = $(this).parent().parent().parent().parent().parent().parent().attr("id");
var ddl = $("#ddlObjectiveGroup option:selected").val();
window.location.replace("ManageTrainingNeeds.aspx?div=" + diva + "&ddl=" + ddl);
});
this alert(div); return undefined.. despite the div vairable in click event has a value
Try encoding the parameters and also canceling the default action in the click event:
function getURLParameter(name) {
return decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
}
$(document).ready(function () {
var div = getURLParameter('div');
var ddl = getURLParameter('ddl');
alert(div + ' ' + ddl);
});
$('.btnAddSub').live('click', function () {
var diva = encodeURIComponent($(this).parent().parent().parent().parent().parent().parent().attr('id'));
var ddl = encodeURIComponent($('#ddlObjectiveGroup').val());
window.location.replace('/ManageTrainingNeeds.aspx?div=' + diva + '&ddl=' + ddl);
return false;
});
Instead of fiddling with the URLs yourself, you could use a library for the job - such as URI.js. (sorry for the self-promo)
$(document).ready(function () {
var search = URI().search(true);
alert(search.div + ' ' + search.ddl);
});
$('.btnAddSub').live('click', function (e) {
var uri = URI('/ManageTrainingNeeds.aspx');
uri.search({
diva: $(this).parent().parent().parent().parent().parent().parent().attr('id'),
ddl: $('#ddlObjectiveGroup').val()
});
window.location.href = uri.toString();
e.preventDefault();
});

trying to replace all \n inside textarea to '\n (4 spaces) ' and viceversa but only one \n is found

here's the link where I'm trying this:
http://jsbin.com/ajirim/2/edit#source
the js code:
$(function(){
$('button').click(dao);
});
function dao() {
var x = $('textarea').val();
if(x.substring(0,4) == ' ')
{
x = x.replace('\n ','\n').substr(4);
}
else
{
x = ' '+ x.replace('\n', '\n ');
}
$('textarea').val(x);
}
You're missing the g flag:
if(x.substring(0,4) == ' ')
{
x = x.replace(/\n {4}/g,'\n').substr(4);
}
else
{
x = ' '+ x.replace(/\n/g, '\n ');
}

Categories