After a long time here and using all your information and comments, I was able to solve all of my code problems. Actually, I don't speak too much English. Sorry for that. Anyway, here we go!
I'm doing business practices and they gave me a project and I've almost finished it, but I cannot deal with it:
I have to detect the OS user system by JS and then after that, if the client is using Windows, I should advise him that he can install a ".exe" to run this app via desktop displaying just a div within a description (here is the div — just a rectangle in this case, so, it doesn't matter). After trying for all of this afternoon, I couldn't solve it and I decided to still testing in at home:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>radio button test [FAILED haha]</title>
<link rel="stylesheet" href="index.css">
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
document.getElementById("good").checked = true;
}else{document.getElementById("bad").checked = true;}
});
if($(#good).is(":checked")){
$(#ident).style.display = "block";
};
</script>
</head>
<body>
<center>
<div id="ident"></div>
<form action="">
<input type="radio" name="system" id="good" value="good">Windows<br>
<input type="radio" name="system" id="bad" value="bad">others
</form>
</center>
</body>
</html>
The problem: I tried to use jQuery to use the Change event on input#windows. The problem is, if it's the default option, the div won't appear, and, if i try it inside out.
I'm done T.T
In advance, thanks.
PS: it's my first post, so if I did something wrong, sorry!
Your problem is that you are not listening to the changeevent. You will have to do that, and when the change event is fired, decide what to do based on the checked/unchecked status of the radio buttons. Also, since you mention that listening to change event doesn't do anything to the radio buttons on page load, that is because you are not evaluating the checked/unchecked status on page load.
p/s: And you forgot to wrap your selector in quotes.
Therefore, the solution is to fire a function on both page load (or DOM ready) and upon change:
$(document).ready(function() {
var systemName = navigator.platform;
if (systemName.indexOf('Win') != -1) {
$('#good').prop('checked', true);
} else {
$('#bad').prop('checked', true);
}
var updateIdent = function() {
if ($('#good').is(":checked")) {
$('#ident').show();
} else {
$('#ident').hide();
}
}
// Update when change event is fired
$('form input[type="radio"]').on('change', updateIdent);
// Update upon DOM ready
updateIdent();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ident">IDENT</div>
<form action="">
<input type="radio" name="system" id="good" value="good">Windows
<br>
<input type="radio" name="system" id="bad" value="bad">others
</form>
Your markup is fine, you're just missing some quotes in your jquery and having problems setting the display: block; This JS will fix it:
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
document.getElementById("good").checked = true;
}else{
$document.getElementById("bad").checked = true;
}
});
if($('#good').is(":checked")){
$('#ident').css('display','block');
};
However, unless you specifically need the radio buttons, you can do without them entirely. Some JS like this will work best:
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
$('#ident').css('display','block');
}else{
$('#ident').css('display','none');
}
});
Hope that helps!
Try this:
$('.radioBtn').change(function () {
if (this.value == 'good') {
$('#ident').show();
} else if (this.value == 'bad') {
$('#ident').hide();
}
});
systemName = navigator.platform;
if (systemName.indexOf('Win') > -1) {
$('#good').prop("checked", true).change();
} else {
$("#bad").prop("checked", true).change();
}
See it in action: https://jsfiddle.net/fmotankv/24/
Also, note that my Fiddle uses CSS to automatically hide the #ident div. I would recommend this method to avoid non-Windows users from potentially seeing the div flash on their screen before being removed by the code.
Related
I want to use jquery to always hide an element when it is checked, and show the element when it is unchecked. After doing some research I found the "is" attribute and so I created a simple html file as:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
if($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p id="test">This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<input type="checkbox" id="s">Click me</input>
</body>
</html>
Now for some reason, the jquery is not functional. Any help would be appreciated please. I also tried:
if(document.getElementById('isAgeSelected').checked) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
And this doesn't work either.
This is simple in javascript. Please try the following:
var cb = document.getElementById('isAgeSelected');
var txtAge = document.getElementById('txtAge');
$(document).ready(function(){
cb.change= function(){
if(cb.checked) {
txtAge.style.display ='block';
} else {
txtAge.style.display ='none';
}
};
});
In JQuery, you can do the following:
$(document).ready(function(){
$('#s').on('change', function(){
if($(this).is(":checked")){
$('#txtAge').show();
}
else{
$('#txtAge').hide();
}
});
});
You are only checking the checkbox once after the DOM is ready instead you should do it on its change event
$("#s").change(function(){
if($(this).is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
You can do this using following jQuery onchange event and .checked function
$(document).ready(function(){
$('#s').change(function(){
if(this.checked)
$("#test").hide(); // checked
else
$("#test").show();
});
});
Working URL:: https://jsfiddle.net/qn0ne1uz/
Good question !
now you were almost there.
$(document).ready(function(){ // <= !! you only evaluete the chackbox once (on document ready)
if($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
What you want to do is monitor checkbox the whole time, like so:
$('#s').bind('change', function() {
if ($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
example on jsfiddle
I'm guessing you are wanting to use the jQuery when the checkbox changes - at the moment you are just changing the hide / show it when the document loads.
Also ids need to be unique or jQuery will only get the first item with that id it comes to when you use the id selector. Change the test id to a class.
If you want the click me to change the state of the checkbox, turn it into a label (think you had it as a button) and target the input (using either for="input-id or wrap the label around the input and the text)
Try the following:
// this is to go in your document ready
$('#s').on('change', function() { // bind to the change event of the chackbox
// inside any change event, this is the js object of the thing that changed (ie the checkbox)
if (this.checked) {
$('.test').hide();
} else {
$('.test').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>This is a heading</h2>
<!-- ids need to be unique so change this to a class or your jquery won't work -->
<p class="test">This is a paragraph.</p>
<p class="test">This is another paragraph.</p>
<input type="checkbox" id="s"><label for="s">Click me</label>
Problem
I have been following this simple tutorial found here. However, I want to modify it so that the calculator is only invoked when the client clicks submit. However, when I click the submit button, no action is observed. I am not even seeing the alert.
EDIT:
I have modified the code per Ojay's suggestions. However, I am getting this error when I try to debug. I am getting this exact issue except I have VS13 Update 3. Multiple things going on here?
Code
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Sample Calculator</title>
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#my-calc').on('submit', function () {
alert("This button is working?");
calculate();
});
function calculate()
{
alert('hi');
//Add
try {
$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));
} catch (e) {
}
//Subtract
try {
$('#sub').val((parseInt($('#num1').val())) - parseInt($('#num2').val()));
} catch (e) {
}
//Multiply
try {
$('#mul').val((parseInt($('#num1').val())) * parseInt($('#num2').val()));
} catch (e) {
}
//Divide
try {
$('#div').val((parseInt($('#num1').val())) / parseInt($('#num2').val()));
} catch (e) {
}
}
});
</script>
</head>
<body>
<div><h4>Sample Calculator</h4></div>
#using (Html.BeginForm())
{
<p> #Html.Label("Input 1") : #Html.TextBox("num1","0")</p>
<p> #Html.Label("Input 2") : #Html.TextBox("num2", "0")</p>
<p> #Html.Label("Sum ") : #Html.TextBox("sum")</p>
<p> #Html.Label("Sub ") : #Html.TextBox("sub")</p>
<p> #Html.Label("Mult ") : #Html.TextBox("mul")</p>
<p> #Html.Label("Div ") : #Html.TextBox("div")</p>
<button id="my-calc" type="button">Calculate</button>
}
</body>
</html>
Attempts
Put in alert. Not observed.
Rewrote it from documents.on.ready(). See below.
RTFM as seen here
Searched stackoverflow. Didn't find anything that worked.
Edit: I had something originally like the tutorial I was looking at. I had:
$(document).ready(function(){
$('#my-calc').on('submit', function (){ //stuff}
}
I don't understand why my function is not being invoked? My form id is correct. All I want to do is invoke this calculator method so my label's sum, sub, mult, and div display the results.
Please pardon the simplistic nature of this question, but I feel it would be useful for others doing .NET MVC tutorials who might also be having this problem. As a result of this question,
I decided to obtain a book on jQuery. Thanks for your assistance.
You're running your code before your form is rendered. Therefore, $('.my-calc') is returning an empty object, and doing nothing. Also, the selector for an item by ID is $('#my-calc'), your selector was looking for an element with class my-calc
// Passing a function into `$()` makes it run after the DOM is ready.
$(function() {
$('#my-calc').on('submit', function (){
alert("This button is working?");
calculate();
});
});
It looks as though there are multiple issues here.
Firstly your selector must be '#my-calc' to correctly select the submit form. Your jQuery code must be wrapped in a document ready handler (as per your added code), or the code needs to appear after the form. Also when you add a submit event handler then you need to return false to stop the form submitting. And lastly (and perhaps the most important), you cannot nest forms. The #using (Html.BeginForm()) creates a form, and then you are creating another one inside it <form id="my-calc">, this is not valid. What the browser will do is just ignore the inner one, so in other words, there will never be a submit event of the my-calc form, becuase the parent form is what is submitted.
Also because you are just doing a calculation on the page with JavaScript, there is no real need for a form anyway, perhaps just a <button type="button" id="my-calc">Calculate</button> would be better with a click event.
Now your calculate function also has errors
every calculation line is missing a $ in the attempt to get the num1 value
so
$('#sum').val((parseInt(('#num1').val())) + parseInt($('#num2').val()));
should be
$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));
and there is an additional issue with the multiplication one, the input is not #mult its #mul as per your #Html.TextBox("mul").
So all of that together, something like the following should resolve your issues
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Sample Calculator</title>
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#my-calc').on('click', function () {
calculate();
});
function calculate() {
//Add
try {
$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));
} catch (e) {
}
//Subtract
try {
$('#sub').val((parseInt($('#num1').val())) - parseInt($('#num2').val()));
} catch (e) {
}
//Multiply
try {
$('#mul').val((parseInt($('#num1').val())) * parseInt($('#num2').val()));
} catch (e) {
}
//Divide
try {
$('#div').val((parseInt($('#num1').val())) / parseInt($('#num2').val()));
} catch (e) {
}
}
});
</script>
</head>
<body>
<div><h4>Sample Calculator</h4></div>
<p> #Html.Label("Input 1") : #Html.TextBox("num1", "0")</p>
<p> #Html.Label("Input 2") : #Html.TextBox("num2", "0")</p>
<p> #Html.Label("Sum ") : #Html.TextBox("sum")</p>
<p> #Html.Label("Sub ") : #Html.TextBox("sub")</p>
<p> #Html.Label("Mult ") : #Html.TextBox("mul")</p>
<p> #Html.Label("Div ") : #Html.TextBox("div")</p>
<button id="my-calc" type="button">Calculate</button>
</body>
</html>
For ids in jquery, you have to use #my-calc
But frankly, I think you're looking to call calculate on the button click otherwise you're going to have to submit your form every time you press the button, which kinda defeats the purpose of the javascript.
$("input").on("click", calculate);
http://jsfiddle.net/4pwakehm/
Your code isn't working because you don't have # in your Javascript.
# should be in front of the name, to represent an Id.
The . should be in front of the name, to represent an class.
You could is essentially do:
$(document).ready(function () {
$("#my-calc").on("click", function () {
alert("Triggered alert for click.");
});
});
Keep in mind that with $(document).ready utilizes jQuery.
That is an example, you should also use your console in the browser to help debug Javascript. Which will help troubleshoot such issues.
Based on the answer here, I tried to create a similar validation function:
<html>
<head>
<script>
$("#my_name_id").on("change", function() {
if (!$("#my_name_id").val()) {
$("#button_id").attr("disabled", "disabled");
} else {
$("#button_id").attr("enabled", "enabled");
}
});
</script>
</head>
<body>
<form action="" name="test_form" id="test_form_id" method="post">
<input type="text" name="my_name" id="my_name_id" placeholder="Type your name"/>
<button type="submit" id="button_id">My button</button>
</form>
</body>
</html>
In this example, I would like to continually check to see if the input box contains any characters. If it does, then the button should be enabled (clickable). If the input box does not contain any text, then the button should be disabled.
However, in my case the button always remains enabled. What am I doing wrong here?
You should use prop, not attr. After all your code will become simpler:
$("#my_name_id").on("change keyup", function() {
$("#button_id").prop("disabled", !this.value);
})
.trigger('change');
Also note how you can use trigger in order to run initial check on page load automatically. I also included keyup event for this to work as you type.
Demo: http://jsfiddle.net/7nywe/
No enabled attribute in HTML for , so manipulate the disabled attribute:
<script>
$("#my_name_id").on("change", function () {
if (!$("#my_name_id").val()) {
$("#button_id").attr("disabled", "disabled");
} else {
$("#button_id").removeAttr("disabled");
}
}).trigger('change');;
</script>
You should use prop()
$("#button_id").prop("disabled", true); // disabled
$("#button_id").attr("disabled", false); // enabled
You should use prop when you are dealing with boolean types.
I am trying to calculate if a textarea has a length of more than zero, then run a piece of code. I can't get this to work for some reason. I would appreciate help.
Here is my code:
Javascript (including jQuery):
$(document).ready(function () {
if ($('.comments').val().length > 0) {
$('form').attr('action', '?Email');
}
});
HTML:
<form action="?AddToQuote" method="POST">
<textarea name="comments" class="comments"></textarea>
<input type="submit" value="submit" />
</form>
I have tried a lot of different Javascript, none of it is working. Does a Javascript if statement run once the HTML page has loaded? I am positive that the line within the if statement works without the if statement, I have tested it already.
You need to execute that line each time the textarea contents get updated. Thus you need to set up the logic on the DOM ready event but evaluate the condition on each content change in the textarea:
$( document ).ready( function() {
var $comment = $('.comments');
$comment.on( 'change', function( event ) {
if( $('.comments').val().length > 0 ) {
$( 'form' ).attr( 'action', '?Email' );
$comment.off( 'change' );
}
} );
} );
As suggested by #destroydaworld you could also use the keyup event if it is really necessary that the check should be evaluated after each single charcter typed in by the used. This is normally used in combination with character counting. But in your case – as you are trying to add some URL parameter – I guess it is sufficient to listen to the change event.
Your if statement will be executed when the DOM is ready, that is to say when your page is fully loaded. Of course, your textarea is empty at that stage. So your if statement will never be true. You should add an event listener to your textarea like so :
$('.comments').on('keyup', function() {
// Do your IF statement here
});
Do it on the submit event of the form. This way it will only check it one time.
$('form').submit(function(){
if( $('.comments').val() ) {
$('form').attr('action', '?Email');
}
});
or i like to add a hidden input:
$('form').append('<input type="hidden" name="email" value="1">');
or you could just check on the server side if there are any comments to email.
Have you tried this?
http://www.jqeasy.com/jquery-character-counter/
Also, did you try calling your form through an ID instead as ('form') ?
$('#theformid').attr('action', '?Email');
Well you can try the following code. Hope it helps you. I have written the code in JS. You need to call the function on the load of page. Hope this helps!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
window.onload = function display()
{
var txt = document.getElementById("myarea").value;
var len = txt.length;
if (len > 0){
document.write("Sucess"); // if len > 0 do some action
}
else
document.write(txt); //else condition
}
</script>
</head>
<body>
<textarea id="myarea" rows="4" cols="25">
Hello! How are you??
</textarea>
</body>
</html>
i m a beginner.
i want that when a checkbox is checked then it should allow user to write something in a txtbox. initially the txtbox is disabled. what i should write inside the function using jquery
<input type="checkbox" id="cb" />
<label for="cb">label for checkbox</label>
<input type="text" id="txt" disabled="disabled" />
<script type="text/javascript">
$(document).ready(function() {
var checkbox = $('#cb');
var textfield = $('#txt');
checkbox.click(function() {
if (checkbox.is(':checked')) {
textfield.removeAttr('disabled');
}
else {
textfield.attr('disabled', 'disabled');
}
});
});
</script>
working example with visibilty
working example with disabled-state
additionally:
as you are working with asp.net, your assignments should look like, eg:
var checkbox = $('#<%= this.cb.ClientID %>');
you should be aware of the way how the server-controls get rendered either (to choose an appropriate selector).
furthermore: you should also be aware of the fact, that disabled-inputs won't get posted, whereas readonly-inputs are no problem to handle...
$('#mycheckbox').click(function()
{
$("#mytextbox").attr('disabled','');
}
);
$(document).ready(function()
{
//To Disable the Check box on page Load
$('#TextBox').attr('disabled', 'disabled');
//On Click of the Check Box
$('#CheckBoz').click(function()
{
if($('#CheckBoz').is(':checked'))
{
$('#TextBox').removeAttr('disabled');
}
else
{
$('#TextBox').attr('disabled', 'disabled');
}
});
});
I Hope this code works perfectly for you and u jst need to paste it in your page and check the Component name according to it.