Using Razor and javascript within each other - javascript

I want to use a javascript variable in Razor like this :
my html:
#{List<AddTempViewModel> tempsToView = new List<AddTempViewModel>();
tempsToView = (List<AddTempViewModel>)ViewData["tempsToView"];}
#if (tempsToView != null)
{
#foreach (var item in tempsToView)
{
<a class="click" id="#item.TempDocumentId">
<img id="leftSideBarElement" src="#item.TempDocumentAddressUrl" />
</a><br />
}
<form method="post" action="">
<input id="documentNumber" class="form-control" type="text" name=""
placeholder="Email" />
</form>
and my script :
<script>
$(document).ready(function () {
$(".click").click(function () {
var divID = $(this).attr('id');
alert(divID);
var docName = #tempsToView[divID].TempDocumentId
$("#documentNumber").val(docName);
});
});
</script>
but I can't set the index of #tempsToView with divID.
please help me what to do except this.
thank you.

You can't set a Razor variable based on something that's happening in JavaScript. Razor runs server-side, while JavaScript runs client-side, after all Razor has already been run.

Its not really clear what you need but If I get you right... I used to make this mix of Razor and Js but in the long run I realize 2 things:
It looks pretty ugly
It won't run if you move your js code to a separate .js file, because
the Razor engine does not process JS files.
So a simple and elegant solution would be to use data attributes:
#foreach (var item in tempsToView)
{
<a class="click" id="#item.TempDocumentId"
data-document-name="#item.TempDocumentName"
data-document-isbn="#item.TempDocumentIsbn">
<img id="leftSideBarElement" src="#item.TempDocumentAddressUrl" />
</a><br />
}
And then just get the data-property you need like:
$(document).ready(function () {
$(".click").click(function () {
var divID = $(this).attr('id');
alert(divID);
var docName = $(this).attr('data-document-name');
var docIsbn = $(this).attr('data-document-isbn');
//and any other property you may need
$("#documentNumber").val(docName);
});
});
That way you keep, all your HTML/Razor and JS separate, and still functional, a clean code and every element is self-sufficient.

<script>
$(document).ready(function () {
var divID = $(this).attr('id');
alert(divID);
var documentName = $(#Html.Raw(JsonConvert.SerializeObject(tempsToView )))[divID];
console.log(documentName);
});
</script>

Related

How to pass controller data (php) to the content blocks of ContentBuilder?

i've bought the latest ContentBuilder.js from innovastudio.
I've integrated it in my cms and is working fine.
Now i have created new static blocks this works fine also.
But now i try to make dynamic blocks with php data passed from the controller when the page loads but can't seems to make it work.
I know php loads before javascript .But i'm a little bit stuck.
Does someone already have worked with contentbuilder.js and could someone please guide me how to resolve this issue please?
I'm working in laravel 5.8 , i did getelementbyid with javascript and replace the value with the dynamic value .
This works but only for single rows and not collections.-
<script type="text/javascript">
jQuery(document).ready(function ($) {
var DBaddress = '{{$settings[0]['address']}}';
var DBnumber = '{{$settings[0]['number']}}';
var DBpostalcode = '{{$settings[0]['postal_code']}}';
var DBtown = '{{$settings[0]['town']}}';
var DBtel = '{{$settings[0]['telephone']}}';
var DBemail = '{{$settings[0]['email']}}';
var obj = $.contentbuilder({
container: '.container_edit',
imageselect: 'admin/laravel-filemanager',
cellFormat: '<div class="col-md-12"></div>',
rowFormat: '<div class="row"></div>',
framework: 'bootstrap',
});
$('#btnViewSnippets').on('click', function () {
obj.viewSnippets();
});
$('#btnViewHtml').on('click', function () {
obj.viewHtml();
});
/*$('#btnSave').on('click', function () {
save(obj.html());
});*/
document.getElementById("address").innerHTML= DBaddress;
document.getElementById("number").innerHTML= DBnumber;
document.getElementById("postalcode").innerHTML= DBpostalcode;
document.getElementById("town").innerHTML= DBtown;
document.getElementById("tel").innerHTML= DBtel;
document.getElementById("email").innerHTML= DBemail;
});
</script>
Here the section where the page builder is set :
#section('content')
<div class="container_edit">
{!! $page->contentBuilder !!}
</div>
#if( basename(url()->current()) !== $page->slug)
<div class="is-tool" style="position:fixed;width:210px;height:50px;border:none;top:250px;bottom:50px;left:auto;right:30px;text-align:right;display:block">
<button id="btnViewSnippets" class="classic" style="width:70px;height:50px;">+ Add</button>
<button id="btnViewHtml" class="classic" style="width:70px;height:50px;">HTML</button>
<button id="btnSave" data-id="{{$editPageDetails[0]->uuid}}" class="classic" style="width:70px;height:50px;">SAVE</button>
</div>
#endif
#endsection
This is how i could manage to make it work, but again this is for single rows. I would like to have the complete collection so i could create dynamic blocks

Write to a text field and simultaneously copy to another textfield

I have 2 textfield with different ids. what I want to achieve is that when I write to textfield1 that content is immediately copied to the second one and if I edit the second one the first one remains unchanged, but also if I go back to first one and edit it, the content is just appended to the second one.
<input type="text" name="field1" id="f1" />
<input type="text" name="field2" id="f2" />
Code :
<script type="text/javascript">
$(document).ready(function(){
$("#f1").keyup(function(){
$('#f2').val($('#f1').val());
});
});
</script>
Try this,
$(document).ready(function () {
$("#f1").keypress(function (e) {
var val = $('#f2').val();
var code = e.which || e.keyCode;
$('#f2').val(val+(String.fromCharCode(code)));
});
});
Live Demo
you can write like this
<script type="text/javascript">
$(document).ready(function(){
$("#f1").keyup(function(){
var f2Text = $('#f2').val() + $(this).val();
$('#f2').val(f2Text );
});
});
</script>
you can also use the Angular JS which is more efficient and easy to use.
AngularJS
Angular JS will help you to develop SPA(Single Page Application).

How to access JavaScript variable in HTML tags?

I am trying to access JavaScript variable in the href attribute of anchor tag.
JavaScript Function:
<script type="text/javascript">
function fun(ReqTextbox)
{
var queueData =document.getElementById(ResTextbox).value;
//some more code
}
</script>
HTML code:
<body>
<input type="text" value="<%=dynamicValue%>" id="<%=dynamicId%>"/>
<a href="servlet?variablename="<%Eval(queueData)%>" onclick=fun('<%=dynamicvalue%>');>LINK</a>
</body>
I know that I am going to wrong at variablename="<%Eval(queueData)%>".
Can someone please help me how to access and pass JavaScript variable as a query string parameter?
First, I think you made a typo :
function fun(ReqTextbox) {
var queueData = document.getElementById(ResTextbox).value;
//some more code
}
You get ReqTextbox parameter but you use ResTextbox. Then, since Javascript is client-sided, you have to manually update the href tag using href attribute. So your function would be like :
function fun(ReqTextbox) {
var queueData = document.getElementById(ReqTextbox).value;
document.getElementById('myAnchor').href = "servlet?variablename=" + queueData;
//some more code
}
And give your anchor tag an id, myAnchor in my example.
Modify HTML code as given below -
<body>
<input type="text" value="<%=dynamicValue%>" id="<%=dynamicId%>"/>
<div id="example2">
<a href="servlet?variablename="<%Eval(queueData)%>" onclick=fun('<%=dynamicvalue%>');>LINK</a> </div>
</body>
Use this to pass query string -
$("#example2 a").attr("href", url + "?variablename=" + queueData);
If I understand you correctly inside fun() function try to use:
var queueData = this.getAttribute('id');
That way you will get id value when runnning onclick() function.

How to pass Variable from External JavaScript to HTML Form

I have been trying to pass a value from an external javascript file to an HTML form with no luck. The files are rather large so I am not sure I can explain it all but ill try.
Basically a user clicks a link then a js file is initiated. Immediately after a new HTML page loads.
I need this value passed to the HTML page in a form field.
Javascript:
var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };
document.getElementById('adcode').value = divElement();
Afterwards it should be passed to this Form field
HTML Form Field:
<p>Ad Code:<br>
<input type="text" name="adcode" id="adcode"/>
<br>
</p>
Thanks for any help!
Your HTML file needs to reference the JavaScript js file. Have a function in your JavaScript that returns the value that you need. Use JavaScript (I like jQuery) to set the form field to what you need.
JS file:
<script>
var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };
document.getElementById('adcode').value = divElement();
function GetDivElement() {
return divElement();
}
</script>
HTML file:
<p>Ad Code:
<br />
<input type="text" name="adcode" id="adcode"/>
<br />
</p>
<script src="wherever that js file is" />
<script>
window.onload = function() {
document.getElementById('adcode').value = GetDivElement();
}
</script>
Although, really, this might do what you want (depending on what you are trying to do):
<p>Ad Code:
<br />
<input type="text" name="adcode" id="adcode"/>
<br />
</p>
<script src="wherever that js file is" />
<script>
window.onload = function() {
GetDivElement();
}
</script>
Can it be this?:
function divElement(divCode){
return divCode;
}
divElement(document.getElementById('adcode').value);

Pass script tag value to input tag in html

I am trying to pass a particular variable value from the script tag to an input tag. But somehow it is not working.
I am trying to pass variable1 value from the below code from script tag to input tag.
So suppose variable1 value is John then this line in my code will look like this-
<input ONCLICK="window.location.href='some_url&textId=John'">
Below is the code
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
// some code
}
var variable1 = getUrlVars()["parameter1"];
var variable1 = unescape(variable1);
// some more code
</script>
<input ONCLICK="window.location.href='some_url&textId=variable1'">
</body>
</html>
Can anyone explain me what wrong I am doing?
Try it that way:
var variable1 = getUrlVars()["parameter1"];
variable1 = unescape(variable1);
document.getElementById('Apply').onclick = function() {
window.location.href = 'some_url&textID=' + variable1;
};
That attaches a function to the onclick event that exactly does what you want. For the initial input element simply remove the onclick attribute:
<input name="Apply" type="button" id="Apply" value="Apply" />
If you wish to perform inline functions, you need to wrap the code in an executable closure:
<input name="Apply" type="button" id="Apply" value="Apply" ONCLICK="(function() {window.location.href='your_data'})();">
As this can be largely unmaintainable, I recommend you abstract this functionality into a more organized place in your application.
(function(window, $, undefined) {
// assuming you use jQuery
$('#Apply').click(function() {
window.location.href = '';// your code
})
})(window, $);
I may be totally misunderstanding what you want to do, but I hope this helps.
The whole url parameters bit is surely unnecessary.
You can just set the value attribute in the field:
var field = document.getElementById('textfield');
var value = 'Some text';
field.addEventListener("click", function () {
this.setAttribute('value', value);
});
Here's a jsfiddle example: http://jsfiddle.net/LMpb2/
You have it inside the ' ' you need to add it into the string. So try
"window.location.href='some_url&textId='+variable1+';'"
I would change it to the following if your trying to bind the click handler to this input element:
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
// some code
}
var variable1 = getUrlVars()["parameter1"];
var variable1 = unescape(variable1);
document.getElementById("Apply").onclick = function() {
window.location.href='some_url&textId=' + variable1;
}
// some more code
</script>
<input name="Apply" type="button" id="Apply" value="Apply" >
</body>
</html>
I haven't tested it yet but it should work.
at onclick call a function, inside that function set window.locatio.href !
a sample
<script>
var url="www.google.com";
function myfunc(){
alert(url);
}
</script>
<input type="button" onclick="myfunc()" value="btn" >
http://jsfiddle.net/CgKHN/

Categories

Resources